将 C++ 函数导入 Python 程序

Import C++ function into Python program(将 C++ 函数导入 Python 程序)

本文介绍了将 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++ 函数如此简单:

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 内容(使用 extern "C" 以便 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文件(例如使用mingw):

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 程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:将 C++ 函数导入 Python 程序

基础教程推荐