C#应用程序嵌入C/Python解释器

在项目的研发过程中,需要将交互式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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值