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
Right Aligning Text in PDFpcell
C# Windows Forms Application - Updating Gui from Another Thread and Class
How to Avoid Response.End() "Thread Was Being Aborted" Exception During the Excel File Download
Create a Coroutine to Fade Out Different Types of Object
What's the Equivalent of Vb's Asc() and Chr() Functions in C#
Replace Parameter in Lambda Expression
Find Out Username(Who) Modified File in C#
In Mvvmcross How to Do Custom Bind Properties
Cannot Access Non-Static Field
How to Draw a Rounded Rectangle as the Border for a Rounded Form
Different Like Behaviour Between My Application and the Access Query Wizard
Differencebetween Manualresetevent and Autoresetevent in .Net
Wrapping Stopwatch Timing with a Delegate or Lambda
Better Way to Trigger Onpropertychanged
Convert File Path to a File Uri
Running Msbuild Programmatically
Globally Convert Utc Datetimes to User Specified Local Datetimes