Using delegates in C# as callback for C DllImported functions - c#

I'm trying to call functions of a C DLL.
But I got a StackOverflowException so I think something is wrong with the function as parameter.
In detail it looks like this.
C DLL (header file):
typedef struct
{
MyType aType; /* message type */
int nItems; /* number of items */
const MyItems *lpItem; /* pointer to array of items */
} MyStruct;
typedef void (__stdcall *MyCbFunc) (HWND, const MyStruct *);
API(BOOL) RegisterCbFunc (ARGS, MyCbFunc);
In C# I tried this:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct MyStruct
{
MyType aType;
int nItems;
MyItems[] lpItem;
}
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void CallbackDelegate(MyStruct mStruct);
[DllImport("MY.dll", CallingConvention=CallingConvention.StdCall)]
private static extern int RegisterCbFunc(IntPtr hWnd, Delegate pCB);
public static void MyCbFunc(MyStruct mStruct)
{
// do something
}
static void Main(string[] args)
{
CallbackDelegate dCbFunc = new CallbackDelegate(MyCbFunc);
int returnValue = RegisterCbFunc(IntPtr.Zero, dCbFunc);
// here, returnValue is 1
}
This runs as long until the DLL calls the callback function. Then I got an error:
An unhandled exception of type 'System.StackOverflowException' occurred in Microsoft.VisualStudio.HostingProcess.Utilities.dll
Thanks for help.
ANSWER:
I don't know why, but there was an answer which is now deleted?!
I try to recover it. The solution was to use call by reference instead of call by value for the function parameter.
public delegate void CallbackDelegate(ref MyStruct mStruct);

Your C function is expecting a pointer to a MyStruct, but you're telling the C# that it wants a pointer to a function. The difference between a function and a struct is... significant. Perhaps try something like
[DllImport("MY.dll", CallingConvention=CallingConvention.StdCall)]
private static extern int RegisterCbFunc(IntPtr hWnd, Delegate pCB);
static void Main(string[] args)
{
MyStruct mStruct;
int returnValue = RegisterCbFunc(IntPtr.Zero, mStruct);
}
If your C function is filling in the lpItem member of the MyStruct with something it allocates itself, I've got no idea what happens next, but at least it's not going to be trying to overwrite your code.

Related

using nested structure pointers in C/C++ DLL in C#

let say we have following code in a dll written in C-lang, where i try to map some functions defined in the dll as functionpointers, map to their actual functions, i follow following link to get till here
https://learn.microsoft.com/en-us/dotnet/framework/interop/marshaling-different-types-of-arrays
Dlltest.h
typedef struct VersionInfo
{
UINT uMajor;
UINT uMinor;
UINT uMRevision;
} STRUCT_VERSION_INFO;
typedef struct DllTestFPStruct
{
int(*Close) (void);
int(*Init) (STRUCT_VERSION_INFO *sVersInfo);
int(*RegisterClient) (int id);
} STRUCT_DLL_TEST_FP_STRUCT;
typedef struct DllTestMgr
{
STRUCT_DLL_TEST_FP_STRUCT *psItf;
int iDummy;
} STRUCT_DLL_TEST_MGR;
extern "C"
{ __declspec(dllexport) void GetDllTestFP(STRUCT_DLL_TEST_MGR *psFP); }
Dlltest.c
static int Close(void);
static int Init(STRUCT_VERSION_INFO *sVersInfo);
static int RegisterClient(int id);
STRUCT_DLL_TEST_FP_STRUCT sFP =
{
&Close,
&Init,
&RegisterClient,
};
DLLTESTC_API void GetDllTestFP(STRUCT_DLL_TEST_MGR *psFP)
{ psFP->psItf = &sFP; }
static int Close(void)
{ printf("Closed called.\n"); }
static int Init(STRUCT_VERSION_INFO *sVersInfo)
{ printf("Init called.\n");}
static int RegisterClient(STRUCT_VERSION_INFO *sVersInfo)
{ printf("RegisterClient called.\n");}
Now i want to write a c# application which uses this DLL, specially it should make use of the "GetDllTestFP"-Function which maps the functionpointers to their actuall function. right now my C#-Application is as follow:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int FP_DLL_TEST_CLOSE(ref VersionInfo sVersInfo);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int FP_DLL_TEST_INIT(ref VersionInfo sVersInfo);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int FP_DLL_TEST_RC(ref VersionInfo sVersInfo);
[StructLayout(LayoutKind.Sequential)]
public struct DllTestFPStruct
{
public FP_DLL_TEST_CLOSE Close;
public FP_DLL_TEST_INIT Init;
public FP_DLL_TEST_RC RegisterClient;
}
[StructLayout(LayoutKind.Sequential)]
public struct DllTestMgr
{
public IntPtr psItf;
public int iDummy;
}
[DllImport("DllTestC.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern void GetDllTestFP(ref DllTestMgr ps);
static void Main(string[] args)
{
VersionInfo vInfo = new VersionInfo();
DllTestFPStruct dllFPs = new DllTestFPStruct();
DllTestMgr dllTest = new DllTestMgr();
IntPtr buffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(dllFPs));
Marshal.StructureToPtr(dllFPs, buffer, false);
dllTest.psItf = buffer;
GetDllTestFP(ref dllTest); // Funtionpointers are not mapped, still null
dllFPs.Close(ref vInfo);
}
The problem is, that the functions do not get mapped to their actuall functions in the dll.
Any idea how can i achieve my goal?
Thanks
The C# code is:
DllTestMgr dllTest = new DllTestMgr();
GetDllTestFP(ref dllTest);
DllTestFPStruct dllFPs = (DllTestFPStruct)Marshal.PtrToStructure(dllTest.psItf, typeof(DllTestFPStruct));
VersionInfo vInfo = new VersionInfo();
dllFPs.Close(ref vInfo);
You don't need to allocate dllTest.psItf becase in GetDllTestFP you do:
DLLTESTC_API void GetDllTestFP(STRUCT_DLL_TEST_MGR *psFP)
{
psFP->psItf = &sFP;
}
So you copy the address of sFP.
Note that in general this is a bad idea, because you are giving to the "client" direct access to your data (the sFP struct). The alternative is that the client passes the memory (as you wrote before) and then you do:
(*psFP->psItf) = sFP;
(but then remember to free the allocated memory!)
Third alternative, the C-side allocates a block of memory through a shared allocator (one that can be used by C#, so no malloc/new here) and then the C# has to deallocate it.
wrong solution is
STRUCT_DLL_TEST_FP_STRUCT sFP2 = sFP;
psFP->psItf = &sFP2;
The lifetime of sFP2 ends when the method returns. psFP->psItf is now pointing to a piece of stack that doesn't exist anymore. don't do it!
Ah... as written by #Hans Passant, depending on who allocates the memory, the GetDllTestFP can be ref or out. If the memory is allocated by C# then it must be ref, if it isn't allocated (as is now) or is allocated by C++, then out is ok and you'll save on the marshaling in one direction.

Marshalling complex struct from C++ to C#

For a few days now I have been trying to Marshal a complex struct from C++ to C#, basically I have managed to get most of what I am trying to achieve done but now I'm stuck trying to marshal what I believe is a list.
In example I will include what I do get working and where I am stuck.
public: void __thiscall TransactionModule_t::GetTransaction(class Identity_t const &)const
Conformed as follwoing:
// public: void __thiscall TransactionModule_t::GetTransaction(class Identity_t const &)const
[DllImport("Transaction.dll", EntryPoint = "?GetTransaction#TransactionModule_t##Identity_t###Z", CallingConvention = CallingConvention.ThisCall)]
public static extern void GetTransaction(IntPtr iPtr,[Out, MarshalAs(UnmanagedType.LPStruct)] Identity transaction);
[StructLayout(LayoutKind.Sequential)]
[Serializable]
public class Identity
{
public uint Id;
public uint Type;
public Identity(uint id = 0, uint type = 0)
{
this.Id = id;
this.Type = type;
}
}
This is working just fine.
However I want to call a method which gives me the list.
public: void __thiscall TransactionModule_t::GetTransactions(class std::vector<class Identity_t,class std::allocator<class Identity_t> > &)const
And where i am getting stuck:
// public: void __thiscall TransactionModule_t::GetTransactions(class std::vector<class Identity_t,class std::allocator<class Identity_t> > &)const
[DllImport("Transaction.dll", EntryPoint = "long mangled entry point", CallingConvention = CallingConvention.ThisCall)]
public static extern void GetTransactions(IntPtr iPtr,[Out] Transactions transactions);
I tried making a class that fits in between the two.
[StructLayout(LayoutKind.Sequential)]
[Serializable]
public class Transactions
{
public Identity Identity;
public Identity[] List;
}
Is it even possible to call this method, am I missing something here?
Is it even possible to call this method?
No it is not. You cannot supply a std::vector from C# code.
Realistically you are going to need a C++/CLI wrapper.

Function pointer in DLL call - how to handle in C#?

I'm using a native DLL that is called out of my C# application. One of the DLL-functions is defined like this:
int set_line(const int width,fct_line_callback callback)
fct_line_callback itself is defined as
typedef int (*fct_line_callback)(double power,void *userData);
So how can I use this function out of my C#-application? Is there a way to define a C# method to be used as callback-function for this DLL-call?
Thanks!
You have to declare a delegate type that matches the native function pointer. It probably should look like this:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate int fct_line_callback(double power, IntPtr userdata);
Now you can write the pinvoke declaration:
[DllImport("foo.dll", CallingConvention = CallingConvention.Cdecl)]
extern static int set_line(int width, fct_line_callback callback);
If the callback can only be made while set_line() is executing then calling the native function is simple:
public void SetLine(int width) {
set_line(width, MyCallback);
}
private void MyCallback(double power, IntPtr userdata) {
// etc...
}
However, if the callback can be made after set_line() is executed, in other words when the native code stores the function pointer, then you have to make sure that the garbage collector cannot collect the delegate object. Simplest way to do so is by storing the object in a static variable:
static class Wrapper {
private static fct_line_callback callback = MyCallback;
public static void SetLine(int width) {
set_line(width, callback);
}
private static int MyCallback(double power, IntPtr userdata) {
// etc...
}
}

Correct way to call a C DLL method from C#

I'm trying to execute some methods (in this particular case, rdOnAllDone) from a third party DLL, written in C, and looking trough the headers files, I found this:
#ifndef TDECLSDONE
#ifdef STDCALL
#define CCON __stdcall
#else
#define CCON __cdecl
#endif
#define TDECLSDONE
#endif
#define DLLIMP __declspec (dllimport)
DLLIMP int CCON rdOnAllDone (void(CCON *)(int));
After goggling for a way to call this method, I made this:
[DllImport("sb6lib.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int rdOnAllDone(Delegate d);
public delegate void rdOnAllDoneCallbackDelegate();
private static void rdOnAllDoneCallback()
{
Console.WriteLine("rdOnAllDoneCallback invoked");
}
The method was called correctly except that I couldn't get the int parameter. So I tried adding the input parameter int like this
[DllImport("sb6lib.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int rdOnAllDone(Delegate d);
public delegate void rdOnAllDoneCallbackDelegate(int number);
private static void rdOnAllDoneCallback(int number)
{
Console.WriteLine("rdOnAllDoneCallback invoked " + number);
}
But now delegate is called twice and and it crashes the program with the following error " vshosts32.exe has stopped working"
What's the correct way to call this DLL method?
EDIT: Forgot to add the Main method:
public static void Main()
{
rdOnAllDoneCallbackDelegate del3 = new rdOnAllDoneCallbackDelegate(rdOnAllDoneCallback);
rdOnAllDone(del3);
while (true)
{
Thread.Sleep(1000);
}
}
Three things you need to do to make this work right:
you need to tell the pinvoke marshaller about the actual delegate type, using Delegate isn't good enough. That will create the wrong thunk that won't properly marshal the argument. Which is what you saw happening.
you need to tell the marshaller about the calling convention if it isn't __stdcall with the [UnmanagedFunctionPointer] attribute. Getting this wrong imbalances the stack with good odds for a hard crash.
you need to store a reference to the delegate object so that the garbage collector won't collect it. It cannot see references held by native code. Getting this wrong makes the native code fail with a hard crash after the next garbage collection.
So this ought to work better, tweak as necessary:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void rdOnAllDoneCallbackDelegate(int parameter);
[DllImport("sb6lib.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int rdOnAllDone(rdOnAllDoneCallbackDelegate d);
class Foo {
private static rdOnAllDoneCallbackDelegate callback; // Keeps it referenced
public static void SetupCallback() {
callback = new rdOnAllDoneCallbackDelegate(rdOnAllDoneCallback);
rdOnAllDone(callback);
}
private static void rdOnAllDoneCallback(int parameter) {
Console.WriteLine("rdOnAllDoneCallback invoked, parameter={0}", parameter);
}
}
Your delegates signature has to match that of the native callback, also it has to have the UnmanagedFunctionPointerAttribute set appropriately.
In your case like so:
[UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
public delegate void rdOnAllDoneCallbackDelegate(int parameter);
[DllImport("sb6lib.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int rdOnAllDone(rdOnAllDoneCallbackDelegate callback);
Usage:
{
rdOnAllDone(rdOnAllDoneCallback);
}
private static void rdOnAllDoneCallback(int parameter)
{
Console.WriteLine("rdOnAllDoneCallback invoked, parameter={0}", parameter);
}

addressof-operator in c#

In a winapi function I have to pass the address of the callback function
that function has to use.
So I declared a unsafe class and everything, but bool* addressofmyfunction = &GetHandle;
just won't compile!
Please help me or give me an alternative to passing the address like this.
In .NET delegates are used to store pointers to functions. For example if you have the following function:
public int GetHandle(int arg1)
{
return arg1 + 10;
}
it's address will be defined like so:
Func<int, int> addressOfMyFunction = GetHandle;
and you can invoke it like that:
int result = addressOfMyFunction(50);
bool* addressofmyfunction = &GetHandle won't compile in C or C++ either (the correct syntax would be bool (*addressofmyfunction)() = &GetHandle), but you can't do like that. I'm not an expert in interop, but I think you have to use Marshal.GetFunctionPointerForDelegate.
Function pointers are represented by delegates in C#. Since methods aren't moved by the garbage collector, you don't need to pin them (or use unsafe code) to pass them to a Win32 API function.
Example:
using System;
using System.Runtime.InteropServices;
public delegate bool CallBack(int hwnd, int lParam);
public class EnumReportApp {
[DllImport("user32")]
public static extern int EnumWindows(CallBack x, int y);
public static void Main()
{
CallBack myCallBack = new CallBack(EnumReportApp.Report);
EnumWindows(myCallBack, 0);
}
public static bool Report(int hwnd, int lParam) {
Console.Write("Window handle is ");
Console.WriteLine(hwnd);
return true;
}
}
There is a similar example for EnumThreadWindows on pinvoke.net.

Categories

Resources