开发者

C/C++ opaque pointer library

开发者 https://www.devze.com 2022-12-28 07:00 出处:网络
Is there library/header already written to manage C++ objects from C using opaque pointers/handles? I can write one myself, but I would rather use already made solution, especially if it has fortran

Is there library/header already written to manage C++ objects from C using opaque pointers/handles?

I can write one myself, but I would rather use already made solution, especially if it has fortran bindings.

my specific requirements are:

  • wrapper generat开发者_Python百科ion facility (my thought is to use boost preprocessor)
  • handling objects through integer (rather than raw pointers) handles (à la mpi) to provide handle verification and special values and some portability with 64-bit fortran.

Thanks


In C++, simply provide functions

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(); }

and a C header

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

Appropriate accessors with casts to and from void* should be all you need.

Your Fortran compiler may be compatible with extern "C" (particularly if it's compatible with C static libraries) or your C++ compiler may have extern "Fortran". See their manuals.

You might be able to find a code generator to do this for you. If you can, doing it manually is safer of course.


Once you have an interface that looks like C, for the Fortran binding probably you can use the ISO C Binding to instruct the Fortran compiler how to call the C interface. Generally the ISO C Binding provides a standard & portable method of interfacing Fortran & C in both directions, though there are some features of both languages that aren't supported. The following is an example interface that might (untested) work to setup a Fortran binding:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消