Wrapping simple c++ example with ctypes; segmentation fault

后端 未结 1 571
萌比男神i
萌比男神i 2021-01-03 16:28

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

#include 

        
1条回答
  •  北海茫月
    2021-01-03 17:13

    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
    

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

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

    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.

    0 讨论(0)
提交回复
热议问题