首页 > 解决方案 > 使用mongocxx驱动程序在c++中查询mongodb集合并将结果集返回给调用c++程序的python

问题描述

我正在尝试从 python 调用 c++ 程序,该程序使用 mongocxx 连接到 mongo,查询一些数据并将结果集返回给 python。这是我的 C++ 程序。c++程序文件的内容

#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <iostream>

extern "C" std::vector<std::string> data(){

std::vector<std::string> arr;

mongocxx::instance inst{};
mongocxx::client conn{mongocxx::uri{}};

bsoncxx::builder::stream::document document{};

auto collection = conn["watchman"]["testcol"];
auto cursor = collection.find({});

for (auto&& doc : cursor) {
   std::cout << bsoncxx::to_json(doc) << std::endl;
   arr.push_back(bsoncxx::to_json(doc));
}


return arr;

}

要编译我正在使用的 C++ 文件:

g++ --std=c++11 -c -fPIC program.cpp -o program.o $(pkg-config --cflags --libs libmongocxx) -Wl,-rpath,/usr/local/lib

g++ -shared -Wl,-soname,library.so -o library.so program.o

调用 c++ 程序的 python 程序的内容。

import ctypes
from numpy.ctypeslib import ndpointer

lib = ctypes.CDLL('./library.so')
lib.function.restype = ndpointer(dtype=ctypes.c_int, shape=(10,))

res = lib.data()
print res

我得到的错误

Traceback (most recent call last):
  File "d.py", line 4, in <module>
    lib = ctypes.CDLL('./library.so')
  File "/usr/lib64/python2.6/ctypes/__init__.py", line 353, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: ./library.so: undefined symbol: _ZN8mongocxx7v_noabi3uri13k_default_uriE

任何帮助,将不胜感激。

标签: pythonc++mongodbctypesmongo-cxx-driver

解决方案


推荐阅读