Skip to content

Calling Python function from C++ #102

@tfgsupport

Description

@tfgsupport

Hi,

Please can you help explain how a user defined C++ class instance can be passed as an argument to a Python function. I am able to pass an integer argument using the PyInt_FromLong function as below.

	int MyClass::getSquare( int x )
	{
		return pow( x, 2 );
	}
	BOOST_PYTHON_MODULE( Test )
	{
		class_<MyClass>( "MyClass" )
			.def( "getSquare", &MyClass::getSquare )
			;
	}

	PyObject * py_args_tuple = PyTuple_New(1);
	PyObject * py_int;
	py_int = PyInt_FromLong( 4 );
	PyTuple_SetItem( py_args_tuple, 0, py_int );
	PyObject_CallObject( pFun, py_args_tuple );

        def getSquare( x ):
                        // Create MyClass object myClass
			print myClass.getSquare(4)

Thanks,

Nilufar

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions