如何使用C ++类与ctypes? [英] How to use C++ classes with ctypes?

查看:151
本文介绍了如何使用C ++类与ctypes?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用ctypes,并希望使用一个C + +类,我已经导出一个dll文件从python使用ctypes。
所以我们可以说我的C ++代码看起来像这样:

  class MyClass {
public:
int test();
...



我会知道创建一个包含这个类的.dll文件,然后使用ctypes在python中加载.dll文件。
现在我如何创建一个类型为MyClass的对象并调用其测试函数?这是甚至可能与ctypes?或者,我会考虑使用SWIG或Boost.Python,但ctypes似乎是小项目的最简单的选项。

解决方案

对于C ++没有标准的二进制接口。对于同一个C ++动态库,不同的编译器输出不同的二进制文件,因为名称调用和不同的方式来处理库函数调用之间的堆栈。



因此,不幸的是,一般来说,实际上没有一种可移植的方式来访问C ++库 。但是,对于一个编译器一次,这没有问题。 -be-a-pain-due-to-politics-Bothering-language-creators-is-fun .... html>这篇博客文章还简要概述了为什么这不会工作。也许C ++ 0x出来后,我们会有一个标准的ABI为C ++?在那之前,你可能不会有任何方法通过Python的 ctypes 访问C ++类。


I'm just getting started with ctypes and would like to use a C++ class that I have exported in a dll file from within python using ctypes. So lets say my C++ code looks something like this:

class MyClass {
  public:
    int test();
...

I would know create a .dll file that contains this class and then load the .dll file in python using ctypes. Now how would I create an Object of type MyClass and call its test function? Is that even possible with ctypes? Alternatively I would consider using SWIG or Boost.Python but ctypes seems like the easiest option for small projects.

解决方案

The short story is that there is no standard binary interface for C++ in the way that there is for C. Different compilers output different binaries for the same C++ dynamic libraries, due to name mangling and different ways to handle the stack between library function calls.

So, unfortunately, there really isn't a portable way to access C++ libraries in general. But, for one compiler at a time, it's no problem.

This blog post also has a short overview of why this currently won't work. Maybe after C++0x comes out, we'll have a standard ABI for C++? Until then, you're probably not going to have any way to access C++ classes through Python's ctypes.

这篇关于如何使用C ++类与ctypes?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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