Wrap templated code?

Asked by nbecker

Can pybindgen wrap templated code? (Functions? Classes?)
Works with/without pygccxml?

Question information

Language:
English Edit question
Status:
Answered
For:
PyBindGen Edit question
Assignee:
No assignee Edit question
Last query:
Last reply:
Revision history for this message
Gustavo Carneiro (gjc) said :
#1

PyBindGen has support for templated functions, methods, and classes. However, for each possible template instantiation you want to support, you have re-declare the wrapper with a combination of template parameters, and multiple wrappers become available in Python side with template parameters combined with the base name (name mangling).

For templated functions, there's an "example" in the unit tests (tests/foo.h):

template <typename T>
std::string TypeNameGet (void)
{
  return "unknown";
}

To wrap this, you would write (I forgot it in tests/foomodulegen.py but the pygccxml scanner picks it up):

    module.add_function('TypeNameGet',
                        'std::string',
                        [],
                        template_parameters=['int'])

The function then becomes available as module.TypeNameGet__lt__int__gt__(). Yes, the name mangling is ugly, I know :|

There's a 'custom_name' parameter available in add_function that would allow you to provide your chosen own name and bypass name mangling, but I just realized I forgot to implement it for plain functions (but I'll fix it ASAP). It is available in class methods, however.

For C++ class methods it is quite similar. For C++ classes themselves, it is also similar, with the parameters "template_parameters", "custom_template_class_name" allowing you to wrap templated classes.

Support for this in the pygccxml based scanner is semi-automatic. First you have to understand that GCC-XML only reports instantiations of methods and functions that are actually used. See http://language-binding.net/pyplusplus/documentation/how_to/templates.html for more information. Second, to provide custom names for specific template instantiations, an annotation is used. Example:
// -#- template_instance_names=type1,type2=>FuncCustomName1|type4,type5=>FuncCustomName2 -#-

I think the template_instance_names annotation is only being supported for functions and methods, not classes. However, if you scan a header file with an appropriate typedef, the problem can be solved: typedef MyClass<Foo, Bar> MyClassWithCustomName;

Revision history for this message
Gustavo Carneiro (gjc) said :
#2

*sigh* the 'template_instance_names' annotation is not yet implemented for functions. I am implementing it right now, will be available in trunk.

Revision history for this message
Gustavo Carneiro (gjc) said :
#3

Function templates fixed in rev. 532.

Can you help with this problem?

Provide an answer of your own, or ask nbecker for more information if necessary.

To post a message you must log in.