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

Hans 1 Reputation point
2020-10-27T00:43:58.4+00:00

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.
}

Not Monitored
Not Monitored
Tag not monitored by Microsoft.
38,543 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Dylan Zhu-MSFT 6,416 Reputation points
    2020-10-27T05:24:21.773+00:00

    Hi Hans-7890,

    I found a similar issue on stack overflow: How to pass function pointer from C# to a C++ Dll?, maybe it could help you.

    And since this issue is more related to Visual C#, which is not supported in Microsoft Q&A forum currently. We recommend you could go to msdn forum: Visual C#, and the community members will provide dedicated support for you.

    Best Regards,
    Dylan

    ---
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.