前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python和c交互

python和c交互

作者头像
sofu456
发布2022-10-28 14:46:36
1.2K0
发布2022-10-28 14:46:36
举报
文章被收录于专栏:sofu456

python调用c++

  • 使用pybind11或者boost.python
代码语言:javascript
复制
char const* greet()
{
   return "hello, world";
}
BOOST_PYTHON_MODULE(hello_ext)
{
    using namespace boost::python;
    def("greet", greet);
}

定义python的函数

  • 使用ctypes调用c模块文件

CDLL(“dll_name.dll”,winmode=0)加载dll,还有WINDLL、PYDLL

python3.8以后版本加winmode、以前的版本不加 导出函数使用extern ”C“ structure结构体封装

代码语言:javascript
复制
class T(structure):
	_fields_=[('a',1),('b',2)]   //添加成员a和b

pointer取地址ctypes类型、id取地址python类型 回调函数调用

代码语言:javascript
复制
def message():
	return "123"
CFUNCTYPE(c_wchar_p)(message)    //返回数据有内存泄漏

类型转换

代码语言:javascript
复制
cast(Point(c_int),c_void_p)    //int*转void*

函数指定参数和返回值

代码语言:javascript
复制
pfunc.create.restype = c_void_p   //指定参数为c_void_p
//c++数据,传入python不声明类型,存在潜在问题
p = pfunc.create()   
pfunc.test(p)    //返回的p不能直接调用

c调用python

使用python的头文件Python.h

  • 执行python字符串的调用方式,返回值在控制台中需要捕获
代码语言:javascript
复制
string line;
std::error_code ec;
boost::process::ipstream is;
boost::process::system("where python", process::std_out>is, 
    ec,process::windows::create_no_window);
std::getline(is, line);
Py_SetPythonHome(boost::locale::conv::to_utf<wchar_t>(
    boost::filesystem::path(line).parent_path().string(), "gbk").c_str());
Py_Initialize();
if(!Py_IsInitialized()){
    cout<<"init python error";
    return -1;
}
PyRun_SimpleString(("import sys\nsys.path.append(r'"+boost::filesystem::path(argv[1]).parent_path().string()+"')").c_str());
  • 执行字符串,表达式并返回值
代码语言:javascript
复制
//#define Py_single_input 256   
//#define Py_file_input 257
//#define Py_eval_input 258         //
//#define Py_func_type_input 345
PyRun_String(ss.str().c_str(), Py_single_input ,py_dict,py_dict);
  • 执行单个函数,Py_BuildValue转换c的类型为python类型
代码语言:javascript
复制
PyRun_SimpleString(("import sys\nsys.path.append(r'"+filesystem::path(argv[1]).parent_path().string()+"')").c_str());
PyObject* pyModule = PyImport_ImportModuleNoBlock(filesystem::path(argv[1]).stem().string().c_str());
if (pyModule != NULL) {
    PyObject* pyFunc = PyObject_GetAttrString(pyModule, filesystem::path(argv[1]).stem().string().c_str());
    if (pyFunc != NULL) {
        if (PyCallable_Check(pyFunc) != 0){
            PyObject* result = NULL;
            //PyObject* arg = Py_BuildValue("s",argv[2]);
            result = PyObject_CallFunction(pyFunc,argv[2]);
            //result = PyObject_CallObject(pyFunc, NULL);
            //Py_DECREF(arg);
            //if (result != NULL) Py_DECREF(result);
            cout << (char*)PyUnicode_DATA(PyObject_Str(result));
        }
        //Py_DECREF(pyModule);
    }
}

异常问题

  • Py_DECREF链接失败

Py_DECREF函数调试和发布的lib不同,需要对应正确的版本才行,用release替换debug是不行的,建议导入python.org官网下载编译(源码项目有bat和configure文件可以编译)

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-10-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • python调用c++
  • c调用python
  • 异常问题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档