带有 boost 的 Python 的 C++ 扩展不起作用

c++ extension for python with boost doesn't works

本文关键字:扩展 不起作用 C++ Python boost 带有      更新时间:2023-10-16

我有一个小的 c++ 模块:(这段代码很糟糕,但它只是原型)

librecv.cpp:

#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <string>
#include <stdio.h>
#include <cstdlib>
typedef boost::interprocess::allocator<float, boost::interprocess::managed_shared_memory::segment_manager>  ShmemAllocator;
typedef boost::interprocess::vector<float, ShmemAllocator> DataVector;
void _init()
{
    printf("Initialization of shared objectn");
}
void _fini()
{
    printf("Clean-up of shared objectn");
}
void work()
{
    boost::interprocess::managed_shared_memory segment(boost::interprocess::open_only, "MySharedMemory");
    DataVector *myvector = segment.find<DataVector>("MyVector").first;
    for(int i = 0; i < 100; ++i)  //Insert data in the vector
    {
        printf("%f ", (float)myvector->at(i));
    }
};

我想在我的 python 代码中使用函数"work"我尝试编译C++库:(我可能会错过这里的东西吗?

g++ -fPIC -c librecv.cpp  -lboost_system -lrt 
g++ -shared -o libtest.so.1.0 -lc librecv.o

蟒蛇代码:

from ctypes import *
libtest = cdll.LoadLibrary('./libtest.so.1.0') #python should call function "_init"  here, but nothing happens
libtest.work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/ctypes/__init__.py", line 378, in __getattr__
    func = self.__getitem__(name)
  File "/usr/lib/python2.7/ctypes/__init__.py", line 383, in __getitem__
    func = self._FuncPtr((name_or_ordinal, self))
AttributeError: ./libtest.so.1.0: undefined symbol: work

操作系统:乌班图有出路吗?PS对不起我的写作错误。英语不是我的母语

C++混淆名称(函数,类,结构,联合等)(见这里)。

您可以通过运行以下命令找到共享对象中实际导出的名称:

/usr/bin/nm libtest.so.1.0

在您的情况下,work() 函数可能正在被破坏以_Z4workv()