简体   繁体   English

将C ++源代码用于f2py时的未定义符号

[英]Undefined symbol when using C++ source for f2py

I can wrap a C function with f2py as follows: 我可以用f2py包装一个C函数,如下所示:

foo.c foo.c的

#include <stdio.h>

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

The corresponding interface file is 对应的接口文件是

foo.pyf 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 然后,我执行f2py foo.pyf -c foo.c -m foo ,这将创建Python库,例如代码

import numpy as np
import foo

foo.func( np.ones(3) )

prints 3 as you would expect. 如您所愿打印3

Problem: changing foo.cfoo.cpp results in undefined symbol 问题:更改foo.cfoo.cpp导致未定义符号

By changing the extension of foo.c to foo.cpp , I notice that 通过将foo.c的扩展名更改为foo.cpp ,我注意到

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

calls g++ instead of gcc . 调用g++而不是gcc Fine. 精细。 However, afterwards when I execute, import foo in Python, I see: 但是,在执行之后,在Python中import foo时,我看到:

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? 我必须运用什么魔术才能使f2py与C ++代码f2py工作? 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. 如果删除接口文件中的intent(c) foo行,则foo.c产生相同的行为,即,从f2py导入时,使用f2py编译f2py产生相同的未定义符号错误。

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. 为了区分C ++甚至允许非类函数使用的重载名称,C ++名称与它们的“ C”名称相比,在链接器中保留的名称要复杂得多。

You can declare a function as extern "C" so that it is exported using the C naming convention. 您可以将函数声明为extern "C"以便使用C命名约定将其导出。 The body of the function can still use c++ features, but it should then be visible to f2py, or similar. 该函数的主体仍可以使用c ++功能,但是f2py或类似的对象应该可以看到它。

Note that this stops you from using C++ name overloading on that function name. 请注意,这将阻止您在该函数名称上使用C ++名称重载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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