Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
Hello everyone
I have a project that transfers data back and forth to a third party software. The communication is made possible via a DLL. One of the functions in the DLL is to send a stream of data with a known length when the data is available (data is a frame). In order for my code to get this data properly I have to use a pointer to the frame. I have tried to use a string variable but I get garbage.
In order to use a pointer in c# I have to use it in unsafe context.
Here is how I create a delegate and point it to the dll:

unsafe delegate int delOnNewFrame(void *a, int b);
delOnNewFrame OnNewFrame;

C#
[System.Runtime.InteropServices.DllImport("someDLL.DLL", EntryPoint = "_SetCallback_OnNewFrame@4")]
static extern int SetCallback_OnNewFrame(delOnNewFrame ptr);


Everything compile other than the part that I set the call back to the function in my code (onNew_Frame). Right here:

C#
OnNewFrame = new delOnNewFrame(OnNew_Frame);
SetCallback_OnNewFrame(OnNewFrame);


"new delOnNewFrame(OnNew_Frame);" becomes underlined and I get:
"error CS0214: Pointers and fixed size buffers may only be used in an unsafe context"
Here is my function which compiles fine as well:

C#
private unsafe int OnNew_Frame(char * pBuffer, int frameCounter)
     {

         return New_Frame((short*)(pBuffer), frameCounter);
     }


My question is how do I correct this issue? how do I assign onNewFrame in unsafe context?
Is there a better way of using pointers in C# in this case?
The code is in .Net 4.0 VS2010. I have checked the "compile unsafe code" in the build option.
Thanks in advance.
Posted
Updated 18-May-12 5:26am
v2

1 solution

Hi there,

I think this will solve your issue. See the third code sample on this page:
http://msdn.microsoft.com/en-us/library/chfa2zb8(v=vs.71).aspx[^]

You need to do something like:
C#
unsafe
{
    OnNewFrame = new delOnNewFrame(OnNew_Frame);
}


Hope this helps,
Ed
 
Share this answer
 
Comments
Member 8456258 18-May-12 12:29pm    
Awesome, This did the trick! Thanks
Ed Nutting 18-May-12 12:32pm    
Glad I could help :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900