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

标签 c++ python boost

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

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 object\n");
}
void _fini()
{
    printf("Clean-up of shared object\n");
}
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

Python代码:

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

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

最佳答案

C++ 破坏名称(函数、类、结构、 union 等...)(参见 here)。

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

/usr/bin/nm libtest.so.1.0

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

关于带有 boost 的 python 的 C++ 扩展不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14629469/

相关文章:

c++ - 如何将 boost::asio::tcp::io_stream 附加到我的 io_service?

c++ - 使用 Boost Python 有条件地添加模块

c++ - 从 QTreeWidget 中删除当前选定的项目

c++ - 使用accumulate时,C++中的operator+不匹配

c++ - vector 相关的内存分配问题

python - 获取下一张和上一张图像的最佳方式 Django

Python 的 os.path 在希伯来语文件名上窒息

c++ - 如何从 MFC 程序写入标准输出?

python - 计算后续字母

c++ - 使用 C++11 时出现错误 "Error: stray character"