3

I have C++ source & headers for a set of libraries which I need to call from a C# application. I've created a managed C++ wrapper around the functions I need and am able to call them from C# marshalling the data backwards and forwards.

Now the hard part..

My unmanaged C++ library generates status messages as it runs and I'd like to be able to display these from the calling C# application. My current thinking goes like this:

I'd like the unmanaged C++ library code to call a function in my C# code that I pass to the managed wrapper as I create it. I've found a few tutorials on Code Project but the syntax seem to be out of date.

If anyone has some sample code or could point me in the direction of a good tutorial that would be great.

Thanks in advance for any help.

Richard Adams
  • 591
  • 1
  • 9
  • 23
  • How exactly does the syntax seem out of date? Can you give us an example? – Cody Gray - on strike Apr 25 '11 at 16:16
  • Are you looking to do a callback since you say the c++ is a library why does your library need to call your code. – rerun Apr 25 '11 at 16:16
  • Are you using managed C++ (old syntax) or C++/CLI (new syntax)? If you are not sure, do you use `^` as the pointer for managed objects in your C++ or `*` – Lou Franco Apr 25 '11 at 16:16
  • Hi Lou, I'm using the new C++/CLI syntax. The old style syntax I mentioned came from a turorial here http://www.codeproject.com/KB/mcpp/unmanaged_to_managed.aspx. – Richard Adams Apr 25 '11 at 16:22
  • Hi rerun, the intention of the callback is to pass status messages back to the calling appliction. They take the form of strings that I'd like to display in the C# GUI. – Richard Adams Apr 25 '11 at 16:23

1 Answers1

2

You can pass a .NET delegate to a C++/CLI function that takes a pointer to a function with "matching" arguments.

Caveats

  1. The pointer-to-function must be STDCALL calling conventions
  2. If the delegate is a member of an object, this pointer to function will not count as a reference to keep the object alive. You have to maintain a reference to the object during the time that the callback is held

Since you think your examples are out of date, I am going to assume you are using the new syntax of C++/CLI. Here is a CodeProject with an example of how to do that

http://www.codeproject.com/KB/mcpp/FuncPtrDelegate.aspx

Lou Franco
  • 87,846
  • 14
  • 132
  • 192
  • Hi Lou, thanks for that it defiantly got me started. For anyone else whose interested I also just found this http://msdn.microsoft.com/en-us/library/367eeye0(v=vs.80).aspx which helped make sense of things. – Richard Adams Apr 25 '11 at 17:34
  • Pay careful attention to point #2 in my answer or your object might get GC'd before you call back into it. The existence of the pointer-to-function does not hold a reference. – Lou Franco Apr 25 '11 at 18:27