C# "Unmanaged Exports"

Unmanaged Exports and delegates

It's pretty simple. You define a delegate type just as you would with a standard p/invoke.

Here's the simplest example that I can think of:

C#

using RGiesecke.DllExport;

namespace ClassLibrary1
{
public delegate int FooDelegate();

public class Class1
{
[DllExport()]
public static int Test(FooDelegate foo)
{
return foo();
}
}
}

Delphi

program Project1;

{$APPTYPE CONSOLE}

type
TFooDelegate = function: Integer; stdcall;

function Test(foo: TFooDelegate): Integer; stdcall; external 'ClassLibrary1.dll';

function Func: Integer; stdcall;
begin
Result := 666;
end;

begin
Writeln(Test(Func));
end.

Output


666

The default calling convention on the C# side is CallingConvention.Stdcall so I've gone along with that. That's the obvious thing to do.

Returning string from C# to C++ using Unmanaged Exports returns numbers

Couple of problems here.

The format string is wrong. To print a Unicode string using ASCII version of printf, the format specified is %S (note the capital S).

Second, you introduced a memory leak here. After you’re done using the string in C++, you must free the memory by calling CoTaskMemFree (assuming you’re writing code for Windows).



Related Topics



Leave a reply



Submit