我尝试在我的c++程序中使用sympy,并使用下面的嵌入代码来实现这一点。在
int sym_ex(const char * input_expression, const char * output_expression){
PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;
int i;
const char * file = "sympy";
const char * function = "simplify";
Py_Initialize();
//PyRun_SimpleString("from sympy import *\n");
pName = PyString_FromString(file);
/* Error checking of pName left out */
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, function);
/* pFunc is a new reference */
if (pFunc && PyCallable_Check(pFunc)) {
pArgs = PyTuple_New(1);
pValue = PyString_FromString(input_expression);
printf("the string passed %s\n", input_expression);
if (!pValue) {
Py_DECREF(pArgs);
Py_DECREF(pModule);
fprintf(stderr, "Cannot convert argument\n");
return 1;
}
/* pValue reference stolen here: */
PyTuple_SetItem(pArgs, 0, pValue);
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue != NULL) {
printf("Result of call: %s\n", PyString_AsString(pValue));
Py_DECREF(pValue);
}
else {
Py_DECREF(pFunc);
Py_DECREF(pModule);
PyErr_Print();
fprintf(stderr, "Call failed\n");
return 1;
}
}
else {
if (PyErr_Occurred())
PyErr_Print();
fprintf(stderr, "Cannot find function \"%s\"\n", function);
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
else {
PyErr_Print();
fprintf(stderr, "Failed to load \"%s\"\n", file);
return 1;
}
Py_Finalize();
return 0;
}
但是,当我用这个函数编写一个小程序并运行它时
^{pr2}$它给出了以下类型错误。我在VisualC++中运行,Python 2.7.8
Exception TypeError: 'expected string or Unicode object, Integer found' in <module 'threading' from 'C:\Python278\Lib\threading.pyc'> ignored
有人能帮帮我吗?谢谢
这里的问题是调用
String_AsString(pValue)
sympy.simplify("2+2")
的结果是4,它是整数而不是字符串。结果是Python引发了一个TypeError
异常。在如果您想要一个字符串作为结果,您可能应该首先调用
PyObject_Str(pValue)
,然后将其转换为C字符串。在相关问题 更多 >
编程相关推荐