Pybind11 C++ 模块问题

问题描述

我正在尝试获取一个运行从 python 调用 c++ 例程的最小示例。我指的是相关博客 here。我无法从 C++ 代码中获得任何输出。此外,我没有收到任何可以指导我的错误或警告。

最大 cpp

#include <iostream>
using namespace std;

// function declaration
int max(int num1,int num2);

int main () {
   // local variable declaration:
   int a = 100;
   int b = 200;
   int ret;

   // calling a function to get max value.
   ret = max(a,b);
   cout << "In CPP : Max value is : " << ret << endl;

   return 0;
}

// function returning the max between two numbers
int max(int num1,int num2) {
   // local variable declaration
   int result;

   if (num1 > num2)
      result = num1;
   else
      result = num2;

   return result;
}

tasks.py

import invoke

@invoke.task()
def build_max(c):
    "Build the shared library for cpp cmult code"
    print_banner("Building C++ Library")
    invoke.run(
        "g++ -O3 -Wall -Werror -shared -std=c++11 -fPIC max.cpp "
        "-o libmax.so"
    )
    print("* Complete")

def compile_python_module(cpp_name,extension_name):
    invoke.run(
        "g++ -O3 -Wall -Werror -shared -std=c++11 -fPIC "
        "`python3 -m pybind11 --includes` "
        "-I /usr/include/python3.8 -I .  "
        "{0} "
        "-o {1}`python3.8-config --extension-suffix` "
        "-L. -lmax -Wl,-rpath,.".format(cpp_name,extension_name)
    )

@invoke.task(build_max)
def build_pybind11_max(c):
    """ Build the pybind11 wrapper library """
    print_banner("Building PyBind11 Module")
    compile_python_module("pybind11_max.cpp","pybind11_max")
    print("* Complete")

@invoke.task()
def test_pybind11_max(c):
    """ Run the script to test PyBind11 """
    print_banner("Testing PyBind11 Module")
    invoke.run("python3.8 pybind11_max_test.py",pty=True)

max.hpp 头文件

int main();

包装C++代码的pybind11代码(pybind11_max.cpp)

#include <pybind11/pybind11.h>
#include <max.hpp>

PYBIND11_MODULE(pybind11_max,m) {
    m.doc() = "pybind11 max plugin";
    m.def("cpp_function",&main,"find max");
}

我能够编译和构建它invoke build-pybind11-max

回复

==================================================
= Building C++ Library 
* Complete
==================================================
= Building PyBind11 Module 
* Complete

测试代码

#!/usr/bin/env python
import pybind11_max

if __name__ == "__main__":
    answer = pybind11_max.cpp_function()
    print(f"    In Python {answer}")

为了运行测试,我运行 invoke test-pybind11-max I get

==================================================
= Testing PyBind11 Module 

在此处添加更新-

当我从终端运行测试文件 python pybind11_max_test.py 时,出现 Segmentation fault (core dumped) 错误

运行 python3.8 pybind11_max_test.py 时,我得到以下输出

Fatal Python error: _PyArgv_AsWstrList: memory allocation Failed
Python runtime state: initialized

Current thread 0x00007fc24d885080 (most recent call first):
  File "pybind11_max_test.py",line 5 in <module>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)