[Mono-dev] Calling .NET code from unmanaged C

Thomas Harning Jr. harningt at gmail.com
Wed Dec 7 11:41:38 EST 2005


A portable option for this is to have your C code compile into a
library and write a C# program that calls into your C library.

In order to give your C program access to C# functions, you would
want to send delegates into the unmanaged code. One option is to
send in all your delegates through registration functions, another
directly through the program startup function, and yet another loads
the delegates into structs.
(Loading them into structs could lead to near-direct object usage by
using a create_() function to load up a struct with function
pointers and accessors).

A short example.. which I've tested:

C# Program:

using System;
using System.Runtime.InteropServices;

class TestApp {
	delegate int DoFooDelegate(string foo, int doo);

	private int instVar = 0;
	public int DoFoo(string foo, int doo) {
		instVar += doo;
		Console.WriteLine("{0} : {1}", foo, instVar);
		return instVar;
	}

	[DllImport("./test.so")]
	static extern int runProgram(DoFooDelegate doFoo);

	public static int Main(string[] args)
	{
		TestApp appInstance = new TestApp();
		return appInstance.RunApp();	
		// Use instance call to ensure DoFoo's delegation is tied to
		//the instance... (Is that necessary, or is there a better way?)
	}
	int RunApp()
	{
		DoFooDelegate fooDelegate = new DoFooDelegate(DoFoo); // .Net 1.1
syntax... portability in compilation
		return runProgram(fooDelegate);
	}
}

#### END C#
compile any way..
#### C Program/Library

typedef int (*DoFooFPtr)(const char*, int);

int runProgram(DoFooFPtr fPtr)
{
	const int bufferSize = 128;
	char buffer[bufferSize];
	for(int x = 0; x < 20; x++) {
		snprintf(buffer, bufferSize, "Bob counts: %i", x);
		int ret = fPtr(buffer, x);
		printf("Returned ((%i)) from fPtr(\"%s\", %i)\n", ret, buffer, x);
	}
	return 0;
}

#### END C Library
Compile with:    gcc -std=c99 -fPIC -shared test.c -o test.so
####
-- 
Thomas Harning Jr.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 265 bytes
Desc: OpenPGP digital signature
Url : http://lists.ximian.com/pipermail/mono-devel-list/attachments/20051207/66bad67a/attachment.bin 


More information about the Mono-devel-list mailing list