如何使用C++ Dll在Python中

发布于 2025-02-09 08:43:35 字数 139 浏览 2 评论 0原文

我有一个用C ++编写的功能和结构的库。它也可以在CS文件中使用包装器在C#中使用,该包装器描述了从DLL调用功能的C#接口。也就是说,要使用C#API,您只需要一个DLL文件。我该如何为Python做同样的事情?除DLL外,我还拥有.h文件,但没有.cpp文件。

I have a library with functions and structures written in C++. It can also be used in C# using a wrapper in a cs-file, which describes C# interfaces that call functions from a DLL. That is, to use the C# API, you only need a DLL file. How can I do the same for python? In addition to the DLL, I also have the .h file, but not the .cpp file.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清风疏影 2025-02-16 08:43:35

您需要使用 ctypes ,您必须具有C中间层的C中间层 让我们

说我们有一个名为duck.cpp

#include <iostream>

class Duck 
{
public: 
    void quack() {std::cout << "Quck\n";}
};

extern "C" {
  Duck* New_Duck(){return new Duck();}
  void Duck_Quack(Duck* duck) {duck->quack();}
}

文件

g++ -c -fPICK duck.cpp -o duck.o
g++ -shared -Vl,-soname,libduck.so -o libduck.so duck.o

from ctypes import cdll

lib = cdll.LoadLibrary('./libduck.so')

class Duck(object): 
    def __init__(self):
        self.obj = lib.New_Duck()

    def quak(self): 
        lib.quck(self.obj)

if __name__ == "__main__":
    duck = Duck()
    duck.quack()

You will need to use ctypes and you have to have an intermediate layer of C.

Let us say we have a file called duck.cpp

#include <iostream>

class Duck 
{
public: 
    void quack() {std::cout << "Quck\n";}
};

extern "C" {
  Duck* New_Duck(){return new Duck();}
  void Duck_Quack(Duck* duck) {duck->quack();}
}

The compiled, here with G++, I will generate an .so and not a dll as I am on Linux:

g++ -c -fPICK duck.cpp -o duck.o
g++ -shared -Vl,-soname,libduck.so -o libduck.so duck.o

Then in Python

from ctypes import cdll

lib = cdll.LoadLibrary('./libduck.so')

class Duck(object): 
    def __init__(self):
        self.obj = lib.New_Duck()

    def quak(self): 
        lib.quck(self.obj)

if __name__ == "__main__":
    duck = Duck()
    duck.quack()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文