C / Python绑定:指针地址修改

时间:2013-12-07 17:29:14

标签: python c++ ctypes language-binding

来源

C ++

extern "C"
{
    Service* create_service( int port )
    {
        Settings settings;
        settings.set_port( port );

        auto service = new Service( settings );

        std::cout << "create_service returning pointer address: " << service << std::endl;

        return service;
    }

    void release_service( Service* service )
    {
        std::cout << "release_service consuming pointer address: " << service << std::endl;
        delete service;
    }
}

的Python

from ctypes import *

library = cdll.LoadLibrary('distribution/library/libhelpers.dylib')

class Service(object):
    def __init__(self, port):
        self.obj = library.create_service(port)
        print "__init__ address: ", self.obj

    def __del__(self):
        print "__del__", self.obj
        library.release_service(self.obj);

控制台

  

create_service返回指针地址:0x7fc3a0e330e0

     

init 地址:-1595723552

     

del 地址:-1595723552

     

release_service使用指针地址:0xffffffffa0e330e0

     

分段错误:11

错误

  

异常类型:EXC_BAD_ACCESS(SIGSEGV)

     

例外代码:KERN_INVALID_ADDRESS位于0xffffffff914d37a0

构建(cmake)

  

设置(CMAKE_CXX_COMPILER clang ++)

     

set(CMAKE_CXX_FLAGS“-stdlib = libc ++ -std = c ++ 11 -Wall -Wextra -Weffc ++ -pedantic”)

     

add_library(helpers SHARED $ {MANIFEST})

     

target_link_libraries(辅助工具)

描述

将C ++类实例作为指针返回时。 Python收到正确的地址。但是,在以后使用此地址时,它似乎已被修改。

1 个答案:

答案 0 :(得分:2)

看来我给ctypes提供的背景不足。

from ctypes import *

library = cdll.LoadLibrary('distribution/library/libhelpers.dylib')

class Service(object):
    def __init__(self, port):
        library.create_service.restype = c_void_p
        self.obj = library.create_service(port)

    def __del__(self):
        library.release_service.argtypes = [c_void_p]
        library.release_service(self.obj);