gpt4 book ai didi

c++ - 从 Python 调用 C/C++?

转载 作者:行者123 更新时间:2023-11-30 17:04:27 25 4
gpt4 key购买 nike

构建与 C 或 C++ 库的 Python 绑定(bind)的最快方法是什么?

(如果这很重要的话,我正在使用 Windows。)

最佳答案

ctypes模块是标准库的一部分,因此比 swig 更稳定且更广泛可用,这总是给我 problems .

使用 ctypes,您需要满足对 python 的任何编译时依赖性,并且您的绑定(bind)将适用于任何具有 ctypes 的 python,而不仅仅是它编译时所针对的 python。

假设您想要在名为 foo.cpp 的文件中与一个简单的 C++ 示例类进行交互:

#include <iostream>

class Foo{
public:
void bar(){
std::cout << "Hello" << std::endl;
}
};

由于 ctypes 只能与 C 函数通信,因此您需要提供将它们声明为 extern "C"的函数

extern "C" {
Foo* Foo_new(){ return new Foo(); }
void Foo_bar(Foo* foo){ foo->bar(); }
}

接下来你必须将其编译为共享库

g++ -c -fPIC foo.cpp -o foo.o
g++ -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o

最后你必须编写你的 python 包装器(例如在 fooWrapper.py 中)

from ctypes import cdll
lib = cdll.LoadLibrary('./libfoo.so')

class Foo(object):
def __init__(self):
self.obj = lib.Foo_new()

def bar(self):
lib.Foo_bar(self.obj)

一旦你有了它,你就可以这样调用它

f = Foo()
f.bar() #and you will see "Hello" on the screen

关于c++ - 从 Python 调用 C/C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35795939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com