简体   繁体   中英

Undefined symbol when using C++ source for f2py

I can wrap a C function with f2py as follows:

foo.c

#include <stdio.h>

void func(int n, int * a) {
    printf("%d\n", n);
}

The corresponding interface file is

foo.pyf

python module foo
interface
subroutine func(n, a)
    intent(c) func
    intent(c)

    integer, intent(hide)                  :: n = shape(a,0)
    real(kind=8), dimension(n), intent(in) :: a
end subroutine func
end interface
end python module foo

Then, I execute, f2py foo.pyf -c foo.c -m foo , which creates the Python library, and so for example, the code

import numpy as np
import foo

foo.func( np.ones(3) )

prints 3 as you would expect.

Problem: changing foo.cfoo.cpp results in undefined symbol

By changing the extension of foo.c to foo.cpp , I notice that

f2py foo.pyf -c foo.cpp -m foo

calls g++ instead of gcc . Fine. However, afterwards when I execute, import foo in Python, I see:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: ./foo.so: undefined symbol: func_

What magic must I apply to make f2py work with C++ code? Is it possible?

Additional note:

If I remove the line intent(c) foo in the interface file, then the foo.c yields the same behavior, ie, it compiles with f2py gives the same undefined symbol error when import from Python.

Ah, this is almost certainly an issue with name mangling.

C++ names are held in the linker with much more complex "mangled" names than their "C" counterparts in order to distinguish the overloaded names that C++ allows even for non-class functions.

You can declare a function as extern "C" so that it is exported using the C naming convention. The body of the function can still use c++ features, but it should then be visible to f2py, or similar.

Note that this stops you from using C++ name overloading on that function name.

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