gpt4 book ai didi

python - C/Python 绑定(bind) : pointer address modification

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:47:18 26 4
gpt4 key购买 nike

来源

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 returning pointer address: 0x7fc3a0e330e0

init address: -1595723552

del address: -1595723552

release_service consuming pointer address: 0xffffffffa0e330e0

Segmentation fault: 11

错误

Exception Type: EXC_BAD_ACCESS (SIGSEGV)

Exception Codes: KERN_INVALID_ADDRESS at 0xffffffff914d37a0

构建(cmake)

set( 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( helpers restbed )

描述

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

最佳答案

看来我没有为 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);

关于python - C/Python 绑定(bind) : pointer address modification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20444297/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com