In C# how do you pass a function pointer to a C++ dll using DllImport

  • Thread starter Thread starter HansCoder
  • Start date Start date
H

HansCoder

Guest
I have a dll which takes in a function pointer with a const char * as an argument.


I am trying to call this from my C# code using DllImport.
It works in the method where I set it but not if I call it again.

C: Code
The function format: void Log( const char * msg );
To set the function: SetLogger( &Log);
To call the log: RunLog(); // This runs Log("Test")

C# code
public delegate void LogDelegate([MarshalAs(UnmanagedType.LPStr)]string msg);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void SetLogger([MarshalAs(UnmanagedType.FunctionPtr)] LogDelegate logFunction);

[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void RunLog();

public void Logger( string msg )
{
// save msg to a file.
}

// Run first
public void Initialize()
{
SetLogger( Logger );
RunLog(); // This works.
}

// Run second.
public void ReRun()
{
RunLog(); // Fails sometimes does nothing some times null pointer exception.
}


Continue reading...
 
Back
Top