用ctypes包装简单的c ++示例;分段故障 [英] Wrapping simple c++ example with ctypes; segmentation fault

查看:392
本文介绍了用ctypes包装简单的c ++示例;分段故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过添加私有成员变量并将其打印在<$ c中,扩展了此答案中提供的示例$ c> bar() function:

I extended the example provided in this answer by adding a private member variable, and printing it in the bar() function:

#include <iostream>
class Foo{
    private:
        double m;
    public:
        Foo() { m = 2.344; };
        void bar(){
            std::cout << "Hello, number is " << m << std::endl;
        }
};

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

ctypes wrapper不变,为:

The ctypes wrapper was unchanged and is:

from ctypes import *
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()

当我运行python代码(早已经编译了C ++代码之后),我得到了一个分段错误,到 bar()中的 m 的打印。

When I run the python code (after having already compiled the C++ code earlier), I am getting a segmentation fault that I have narrowed down to the printing of m in bar().



  1. 如果我取消打印 m ,但将其保留为变量

  2. $ c> m 与 bar()中的任何固定数字。

  1. in the original code
  2. if i remove printing of m but keep it as a variable
  3. if i substitute m with any fixed number in bar().

我真的很困惑为什么会发生这种情况。因为这是一个学习ctypes的实验,任何帮助将不胜感激。

I am really puzzled why this should be happening. As this is an experiment to learn ctypes, any help would be appreciated.

推荐答案

如果您使用64位Python,则需要定义 restype argtypes 。否则ctypes默认将值转换为32位C int

If you're using 64-bit Python, you need to define the restype and argtypes. Otherwise ctypes defaults to casting the values to a 32-bit C int.

from ctypes import *

lib = CDLL('./libfoo.so')

lib.Foo_new.argtypes = []
lib.Foo_new.restype = c_void_p

lib.Foo_bar.argtypes = [c_void_p]
lib.Foo_bar.restype = None

以下是2.7.5,modules / _ctypes / callproc.c的源代码链接:

Here are source links for 2.7.5, Modules/_ctypes/callproc.c:


  • a href =http://hg.python.org/cpython/file/ab05e7dd2788/Modules/_ctypes/callproc.c#l559 =nofollow> ConvParam (第645-663行)

  • GetResult (第914-915行)

  • ConvParam (Lines 645-663)
  • GetResult (Lines 914-915)

对于64位Windows,C long 是32位,但在大多数其他64位平台上它是64位。通过强制 int ,结果至少是一致的。

For 64-bit Windows a C long is 32-bit, but it's 64-bit on most other 64-bit platforms. By forcing int the result is at least consistent.

这篇关于用ctypes包装简单的c ++示例;分段故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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