[Mono-list] Interop
Jonathan Pryor
jonpryor@vt.edu
Mon, 13 Dec 2004 06:54:09 -0500
On Mon, 2004-12-13 at 10:35 +0100, Javier Miguel Gonzalez wrote:
> I want to call a .Net function (in a class) from unmanaged code, like
> VC++ 6 or Delphi 7.
>
> Do you know if it is possible?
Maybe. It depends on what syntax/functionality you want to enable.
> Are there something like JNI in .Net?
Platform Invoke (P/Invoke) is the closest equivalent to JNI, though
P/Invoke doesn't permit use of .NET classes from unmanaged code, nor
does it offer an equivalent to JNI's reflection mechanisms.
> I have read this articles:
>
> http://www.blong.com/Conferences/BorCon2004/Interop1/Win32AndDotNetInterop.h
> tm#InversePInvoke
This won't work on Mono/Linux, principally because it assumes that the
PE file format is the platform's native file format. Inverse P/Invoke
allows you to make a library export that invokes a .NET function.
However, this library export is a "normal" PE export. While this makes
things brain-dead simple for Windows platforms, it doesn't work for
platforms which don't use PE for the native file format, such as Linux
(which uses ELF).
> http://www.codeproject.com/csharp/Win32_to_NET.asp
This is the recommended approach, and is supported by both Mono
and .NET. Delegates are your friend. :-)
One thing the above article doesn't mention is that the function pointer
the unmanaged code receives lives only as long as the managed delegate.
Once the managed delegate is GC'd, so is the function pointer that the
unmanaged code has, so if the unmanaged code invokes the function
pointer, you could crash the program.
> Are in Mono something better to do it than in MS .Net Framework?
Define "better". If you want portability between Mono and .NET,
delegates are the only portable approach.
If you don't mind being tied to Mono, then you could use the embedding
API, which permits unmanaged code to add additional internal calls,
create new managed objects, and invoke them.
See: http://www.go-mono.com/embedded-api.html
- Jon