[英]ImportError: undefined symbol when importing swigged c++-class in python
我嘗試在 Python 中使用 C++ 類進行套接字通信。 因此,我創建了一個使用nngpp的類。 將 swigged 文件導入 python 時,出現 ImportError: undefined symbol: nng_msg_insert。 類的定義是:
/* commclass.h */
#include <nngpp/nngpp.h>
#include <nngpp/protocol/req0.h>
#include <nngpp/protocol/rep0.h>
#include <nngpp/msg_body.h>
#include <nngpp/msg_header.h>
#include <nngpp/msg.h>
#include <nngpp/socket.h>
#include <nngpp/view.h>
#include <string>
#include <nlohmann/json.hpp>
//#include <thread>
#include <iostream>
#include <cstdio>
#include "/usr/local/include/nng/nng.h"
//#include <memory>
#include <chrono>
using json = nlohmann::json;
class CommIF
{
private:
nng::socket socket;
nng::msg message;
int msg_size;
public:
CommIF(const std::string option, std::string ipToListen, std::string ipToDial)
{
message = nng::make_msg(0);
if (option.compare("rep") == 0)
{
socket = std::move(nng::rep::v0::open());
}
else if (option.compare("req") == 0)
{
socket = std::move(nng::req::v0::open());
}
else
{
printf("EXCEPTION");
}
socket.listen(ipToListen.c_str());
bool connected = false;
while (connected == false)
{
try
{
socket.dial(ipToDial.c_str());
connected = true;
std::cout << "successfully connected\n";
}
catch (const nng::exception &e)
{
std::cerr << e.what() << "; retry in 1 s" << '\n';
//std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
msg_size = 0;
}
};
swig的接口文件是:
/* commclass.i */
%module commclass
%{
#include "src/commclass.h"
%}
%include "src/commclass.h"
然后我從命令python3 build_commclass.py build_ext --inplace
構建過程開始。 文件 build_commclass.py 如下
from distutils.core import setup, Extension
import os
name = "commclass"
version = "0.0.1"
os.environ["CC"] = "g++"
setup(name = name, version = version, ext_modules = [Extension(
name = '_commclass',
sources = ["commclass.i"],#"src/commclass.h"],
include_dirs = ['src'],#'/home/user1/Documents/extLibs','/usr/local/include'],
swig_opts = ["-c++", "-modern"]
)])
當我現在將該類導入到 python 時,出現上述錯誤。 我在 google 和 stackoverflow 上搜索了很多,我很確定這是一個鏈接器問題。 我還使用 distutils.core 的編譯器和鏈接器選項嘗試了很多不同的東西,但我沒有找到解決方案。
編輯 1:我現在更改了接口文件如下
/* commclass.i */
/* module*/
%module commclass
%{
#include "/usr/local/include/nng/nng.h"
#include "src/nngpp/nngpp.h"
#include "src/nngpp/protocol/req0.h"
#include "src/nngpp/protocol/rep0.h"
#include "src/nngpp/socket.h"
#include "src/nngpp/msg.h"
#include "src/nngpp/aio.h"
#include "src/nngpp/aio_view.h"
#include "src/nngpp/msg_body.h"
#include "src/nngpp/msg_header.h"
#include "src/commclass.h"
%}
%include "/usr/local/include/nng/nng.h"
%include "src/commclass.h"
我現在在 python 中導入時遇到相同的錯誤,但未定義的符號已更改。 現在是nng_aio_set_iov
。 nng_msg_insert
和nng_aio_set_iov
都在我現在包含的文件nng_aio_set_iov
中定義。 我現在很困惑。
默認情況下,SWIG 僅為%include
直接指定的定義生成接口。 nng_msg_insert
未在src/commclass.h
定義。 您需要額外的%include
語句來引入定義。
請注意,您可以使用-includeall
SWIG 標志將默認值更改為遞歸到所有#include
語句中,但您通常不希望整個<iostream>
、 <cstdio>
、 <string>
等接口被包裝,並且很可能如果沒有很多額外的努力,將無法工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.