C / C ++不透明指针库

时间:2010-04-25 18:12:04

标签: c++ c interface fortran opaque-pointers

是否已经编写了库/头来使用不透明指针/句柄从C管理C ++对象?

我可以自己写一个,但我宁愿使用已经制作的解决方案,特别是如果它有fortran绑定。

我的具体要求是:

  • 包装器生成工具(我的想法是使用boost预处理器)
  • 通过整数(而不是原始指针)句柄(àlampi)处理对象,以提供句柄验证和特殊值以及64位fortran的一些可移植性。

由于

2 个答案:

答案 0 :(得分:4)

在C ++中,只需提供函数

Foo foo; // C++ object we want to access

Foo &foo_factory(); // C++ function we want to call

extern "C" void * get_foo() // extern "C" so C can call function
    { return (void *) & foo; } // cast it to an opaque void * so C can use it

extern "C" void * create_foo()
    { return (void *) & foo_factory(); }

和C标题

extern void * get_foo();
extern void * create_foo();

应该只需要void*来自extern "C"的演员阵容。

您的Fortran编译器可能与extern "Fortran"兼容(特别是如果它与C静态库兼容)或者您的C ++编译器可能具有{{1}}。请参阅他们的手册。

您可以找到代码生成器来为您执行此操作。如果可以的话,手动操作当然会更安全。

答案 1 :(得分:0)

一旦你有一个看起来像C的接口,对于Fortran绑定,你可以使用ISO C Binding来指示Fortran编译器如何调用C接口。通常,ISO C Binding提供标准&便携式Fortran接口连接方法C在两个方向上,但两种语言的某些功能都不受支持。以下是可能(未经测试)设置Fortran绑定的示例界面:

module my_fortran_binding

use iso_c_binding

implicit none

interface get_foo_interf

   function get_foo () bind (C, name="get_foo")

      import

      type (C_PTR) :: get_foo

   end function get_foo

end interface get_foo_interf


interface create_foo_interf
  etc....
end create_foo_interf

end module my_fortran_binding
相关问题