将C ++函数导入Python程序 [英] Import C++ function into Python program

查看:94
本文介绍了将C ++函数导入Python程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在试验python函数。我已经找到一种方法来将python函数导入到c / c ++代码中,但是没有其他方法。

I'm experimenting with python functions right now. I've found a way to import python functions into c/c++ code, but not the other way around.

我有一个c ++程序,它有一个特定的函数在里面。我想将编译好的c ++程序导入到我的python脚本并调用c ++函数。

I have a c++ program written and it has a certain function in it. I'd like to "import" the compiled c++ program into my python script and call the c++ function.

为简单起见,说c ++函数很简单: / p>

For simplicity, say the c++ function is as simple as:

int square(x)
{
  return x*x;
}

,编译程序命名为Cprog。

and the compiled program is named Cprog.

我想要我的python脚本是:

I'd like my python script to be something like:

import Cprog

print Cprog.square(4)

我在互联网上搜索没有效果,我希望你的一个大师可能有一个聪明的方式去这个...

Is this possible? I've searched the internet to no avail and I'm hoping one of you gurus might have a clever way of going about this...

推荐答案

这里是上面简单示例的一些工作完成。虽然线程很老,我认为对初学者有一个简单的全包指南是有帮助的,因为我之前也有一些问题。

Here is a little working completion of the simple example above. Although the thread is old, I think it is helpful to have a simple all-embracing guide for beginners, because I also had some problems before.

function.cpp content externC使用ctypes模块可以处理函数):

function.cpp content (extern "C" used so that ctypes module can handle the function):

extern "C" int square(int x)
{
  return x*x;
}

wrapper.py内容:

wrapper.py content:

import ctypes
print ctypes.windll.library.square(4) # windows
print ctypes.CDLL('library.so').square(4) # linux or when mingw used on windows

然后编译function.cpp文件例如):

Then compile the function.cpp file (by using mingw for example):

g++ -shared -c -fPIC function.cpp -o function.o

然后使用以下命令创建共享对象库(注意:不是空白):

Then create the shared object library with the following command (note: not everywhere are blanks):

g++ -shared -Wl,-soname,library.so -o library.so function.o

然后运行wrapper.py程序应该工作。

Then run the wrapper.py an the program should work.

这篇关于将C ++函数导入Python程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆