C / Python绑定:指针地址修改 [英] C/Python binding: pointer address modification
问题描述
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 >
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);
控制台
Console
create_service返回指针地址:0x7fc3a0e330e0
create_service returning pointer address: 0x7fc3a0e330e0
init 地址:-1595723552
init address: -1595723552
del 地址:-1595723552
del address: -1595723552
release_service使用指针地址:0xffffffffa0e330e0
release_service consuming pointer address: 0xffffffffa0e330e0
:11
错误
Error
异常类型:EXC_BAD_ACCESS(SIGSEGV)
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
异常代码:KERN_INVALID_ADDRESS,位于0xffffffff914d37a0
Exception Codes: KERN_INVALID_ADDRESS at 0xffffffff914d37a0
(cmake)
Build (cmake)
设置(CMAKE_CXX_COMPILER clang ++)
set( CMAKE_CXX_COMPILER clang++ )
设置(CMAKE_CXX_FLAGS stdlib = libc ++ -std = c ++ 11 -Wall -Wextra -Weffc ++ -pedantic)
set( CMAKE_CXX_FLAGS "-stdlib=libc++ -std=c++11 -Wall -Wextra -Weffc++ -pedantic" )
add_library(helpers SHARED $ {MANIFEST})
add_library( helpers SHARED ${MANIFEST} )
target_link_libraries(helpers restbed)
target_link_libraries( helpers restbed )
说明
作为指针返回C ++类实例时。 Python接收正确的地址。但是,在以后使用此地址时,它似乎已被修改。
Description
When returning a C++ class instance as a pointer. Python receives the correct address. However when using this address at a later date, it appears to have been modified.
推荐答案
看来我给ctypes上下文不足。
It appears I was giving insufficient context to 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);
这篇关于C / Python绑定:指针地址修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!