在项目的研发过程中,需要将交互式Python解释器嵌入到C#应用程序中,而C/Python解释器一般用于嵌入到C++应用程序中,故将Python解释器二次封装为C++动态库,由C#程序调用。在C#应用程序调用C++库时,遇到了字符串传参出现乱码的问题,经过反复调试,现对字符串传参问题进行了彻底解决,如下代码所示:
C++封装Python解释器Dll:
extern "C" _declspec(dllexport) bool RunPythonCode(_In_ LPWSTR PyStr, _Out_writes_to_(nMaxCount, return) LPWSTR OutStr, _In_ int nMaxCount);
bool RunPythonCode(_In_ LPWSTR PyStr, _Out_writes_to_(nMaxCount, return) LPWSTR OutStr, _In_ int nMaxCount)
{
PyRun_SimpleString(stdOutErr.c_str());
int ret = -1;
PyObject* obj = Py_BuildValue("u", PyStr);
ret = PyRun_SimpleString(_PyUnicode_AsString(obj));
PyObject* catcher = PyObject_GetAttrString(pModule, "catchOutErr");
PyObject* output = PyObject_GetAttrString(catcher, "value");
const char* TempStr = _PyUnicode_AsString(output);
int bufSize = MultiByteToWideChar(CP_UTF8, 0, TempStr, -1, NULL, 0);
wchar_t* wp = new wchar_t[bufSize+1.0];
MultiByteToWideChar(CP_UTF8, 0, TempStr, -1, wp, bufSize);
wp[bufSize] = '\0';
swprintf_s(OutStr, nMaxCount, L"%s", wp);
delete []wp;
return ret == 0;
}
C#调用C++动态库:
class NativeMethods
{
[DllImport("PythonInterpreter.dll", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool RunPythonCode(string s, StringBuilder output, int nMaxCount);
}
StringBuilder OutStr = new StringBuilder(NativeMethods.BUFFERSIZE);
NativeMethods.RunPythonCode(ScriptStr, OutStr, OutStr.Capacity);