栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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] = '';
    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);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/769460.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号