![](/img/trans.png)
[英]Can't run tensorboard because of “ Symbol not found: _PyBytes_AsString”
[英]C++ embedded Python PyBytes_AsString causing DLL to crash
試圖使C ++和Python嵌入式DLL正常工作,並且似乎在PyBytes_AsString組件上遇到了麻煩 。
具體來說這行:
strcpy(buffer, PyBytes_AsString(pValue));
它試圖將返回值從milp_closest.solve函數int復制到char緩沖區。 但是它幾乎使DLL崩潰,就像它們是不兼容的類型一樣。
輸入格式 -milp_closest.solve(10,20,30,25)
輸出字符串格式 -(0,1,25.0,[1,1,1,1,1,0,1,1,1,1,1])
// The Function calls a Python module named milp_closest()
// Input parameters: 4 integers
// Output parameters: a string return by the call to the Python module
extern "C" LPCSTR __declspec( dllexport ) __stdcall TS2Py_Milp(int n, int p1, int p2, int average)
{
static char buffer[256]={""};
PyObject *pName, *pModule, *pDict, *pfSolve;
PyObject *pArgs, *pValue;
Py_Initialize();
//pName = PyString_FromString("");
/* Error checking of pName left out */
pModule = PyImport_ImportModule("milp_closest"); // which Python module do we wish to load
//Py_DECREF(pName);
if (pModule != NULL)
{
pfSolve = PyObject_GetAttrString(pModule, "solve"); // which function in the above-loaded module, do we wish use
/* pfSolve is a new reference */
if (pfSolve && PyCallable_Check(pfSolve))
{
pArgs = PyTuple_New(4); //The Solve funciton takes 4 input parameters
pValue = PyLong_FromLong((long) n); // store 1st parameter (n) for function Solve
/* pValue reference stolen here: */
PyTuple_SetItem(pArgs, 0, pValue);
pValue = PyLong_FromLong((long) p1); // store 1st parameter (n) for function Solve
PyTuple_SetItem(pArgs, 1, pValue);
pValue = PyLong_FromLong((long) p2); // store 1st parameter (n) for function Solve
PyTuple_SetItem(pArgs, 2, pValue);
pValue = PyLong_FromLong((long) average); // store 1st parameter (n) for function Solve
PyTuple_SetItem(pArgs, 3, pValue);
pValue = PyObject_CallObject(pfSolve, pArgs); // call the Python funciton "Solve"
Py_DECREF(pArgs);
if (pValue != NULL)
{
strcpy(buffer, PyBytes_AsString(pValue));// copy the RERTURN value(string) form Python function call, in to our return value
Py_DECREF(pValue);
}
else
{
Py_DECREF(pfSolve);
Py_DECREF(pModule);
PyErr_Print();
fprintf(stderr,"Call failed\n");
return "call to function solve() failed";
}
}
else
{
if (PyErr_Occurred())
PyErr_Print();
fprintf(stderr, "Cannot find function \"solve\"\n" );
}
Py_XDECREF(pfSolve);
Py_DECREF(pModule);
}
else
{
PyErr_Print();
fprintf(stderr, "Failed to load \"milp_closest.py\"\n");
return "Failed to laod module <milp_closest.py>";
}
Py_Finalize();
// we return (or pass on) the string returned from the call to the Python function "solve".
return (LPCSTR) buffer;
關於我可能在哪里出錯的任何建議?
首先,請確保您知道導致崩潰的確切行(使用打印語句或通過調試器)。 這將確保我們在調試正確的區域。 另外,嘗試打印從PyBytes_AsString()返回的char *。
其次,您將一個元組傳遞給milp_closest.solve()
函數,但是您的示例傳遞了4個整數。 我想你是這個意思嗎?
PyObject* args = Py_BuildValue("llll", 10, 20, 30, 25);
if (!*args) {
/* handle error */
}
Py_Object* pValue = PyObject_CallObject(pfSolve, args);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.