[Mono-dev] internal call from c# to c++

Robert Jordan robertj at gmx.net
Fri Aug 25 08:05:22 EDT 2006


Erik Christensen wrote:
> Hi,
> 
> Trying to make a program, where it's possible to use C# to script to the
> Core (C++ code).
> 
> I don't want to use P/Invoke.
> 
> I can run the Internal calls  example from 
> http://http://www.mono-project.com/Embedding_Mono
> http://www.mono-project.com/Embedding_Mono  without a problem. And
> everything's fine as long as the function(s) doesn't use any argument(s).
> However, I just can't seem to get a hold of the arguments on the C++ side.
> Can someone pass an advice on this please?
> 
> Testcode is:
> 
> **************
> C# :
> **************
> using System;
> using System.Runtime.CompilerServices;
> 
> class Test
> {
> 
> [MethodImplAttribute(MethodImplOptions.InternalCall)]
>     extern private int calcsum(int a, int b);
> 
> static void Main(string[] args)
>     {
>         Test t = new Test();
>         Console.Write(t.calcsum(3,3));
>     }
> }
> 
> 
> **************
> C++ : (mono embed)
> **************
> //include's
> 
> int calcsum(int a, int b)
> {
>    return (a+b);
> }
> 
> int main(int argc, char* argv[]) 
> {
> 
> //...
> 
> mono_add_internal_call ("Test::calcsum(int,int)", calcsum);
> 
> //...
> }
> 
> It'll compile, and run, however the result is just random numbers from
> somewhere in the memory, which should mean that the "a" and "b" variables
> aren't set from the c# side (ie. the 3 is lost somewhere).


Have a closer look at the signature:

[MethodImplAttribute(MethodImplOptions.InternalCall)]
     extern private int calcsum(int a, int b);

This is an instance member, because "static" is missing.

In this case the C signature must be

int calcsum(void *obj, int a, int b)
{
    return (a+b);
}

Of, if you want to access the MonoObject:

int calcsum(MonoObject *obj, int a, int b)
{
    return (a+b);
}

If your methods are sematically rather static (like in your
sample), just change the managed signature:

[MethodImplAttribute(MethodImplOptions.InternalCall)]
     static
     extern private int calcsum(int a, int b);

Robert




More information about the Mono-devel-list mailing list