简体   繁体   中英

Python argument types did not match c++ signature - Boost.Python

I am just starting to explore using Boost.Python to wrap some c++ code. I am starting with a toy problem to work out the basic issues but don't understand the error I'm getting.

#include "pch.h"
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <boost/python/args.hpp>


class Parameters
{
public:
    int a;
    void seta(int val) { a = val; }
    int geta() { return a; }
    void add(int first, int second) { a = first + second; }

};


BOOST_PYTHON_MODULE(my_lib) {

    boost::python::class_<Parameters>("Parameters")
        .add_property("a", &Parameters::geta, &Parameters::seta)
        .def("add", &Parameters::add, boost::python::args("first", "second"));

}

The python script, also simple is:

#Test program to use simple c++ dynamic library binding

import sys
import my_lib
import ctypes

if __name__ == '__main__':

 
    my_lib.Parameters.a = 9

    result = my_lib.Parameters.a

    print("result = ",result)

    my_lib.Parameters.add(2,3)

    sumresult = badprog_lib1.Parameters.a

    print("sum result = ", sumresult)

When I run the python, I get the following:

result =  9
Traceback (most recent call last):
  File "C:/Users/strat/source/repos/badprog_lib1/LibClient2.py", line 19, in <module>
    my_lib.Parameters.add(2,3)
Boost.Python.ArgumentError: Python argument types in
    Parameters.add(int, int)
did not match C++ signature:
    add(class Parameters {lvalue}, int first, int second)

It is complaining about parameter mismatch between the c++ and Boost.Python arguments. One thing I don't understand is why the C++ signature includes "class Parameters {lvalue}" and am wondering if that's a clue. Any help from you more experienced Boost users would be greatly appreciated.

Your python code is invalid.

my_lib.Parameters.a = 9 creates static variable in class Parameters that is why it "works". Then you try call static method add which doesn't exists, add is instance method so you need instance of Parameters to call it.

So this should work:

import sys
import my_lib
import ctypes

if __name__ == '__main__':
    param = my_lib.Parameters()
    param.add(2, 3)
    print("result = ", param.a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM