问题描述
大家好
我有一个将数据来回传输到第三方软件的项目.通过DLL可以进行通信. DLL中的功能之一是在数据可用时(数据是一帧)发送具有已知长度的数据流.为了使我的代码正确获取此数据,我必须使用指向框架的指针.我试图使用一个字符串变量,但是我得到了垃圾.
为了在c#中使用指针,我必须在不安全的上下文中使用它.
这是我创建委托并将其指向dll的方法:
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;
[System.Runtime.InteropServices.DllImport("someDLL.DLL", EntryPoint = "_SetCallback_OnNewFrame@4")]
static extern int SetCallback_OnNewFrame(delOnNewFrame ptr);
除了我将代码设置回函数中的部分(onNew_Frame)以外,所有内容均会编译.就在这里:
Everything compile other than the part that I set the call back to the function in my code (onNew_Frame). Right here:
OnNewFrame = new delOnNewFrame(OnNew_Frame);
SetCallback_OnNewFrame(OnNewFrame);
"new delOnNewFrame(OnNew_Frame);" 下划线,我得到:
错误CS0214:指针和固定大小的缓冲区只能在不安全的上下文中使用"
这是我的函数,也可以正常编译:
"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:
private unsafe int OnNew_Frame(char * pBuffer, int frameCounter)
{
return New_Frame((short*)(pBuffer), frameCounter);
}
我的问题是如何解决这个问题?如何在不安全的上下文中分配onNewFrame?
在这种情况下,是否有更好的方法在C#中使用指针?
该代码在.Net 4.0 VS2010中.我已经检查了构建选项中的编译不安全代码".
预先感谢.
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.
推荐答案
unsafe
{
OnNewFrame = new delOnNewFrame(OnNew_Frame);
}
希望这会有所帮助,
Ed
Hope this helps,
Ed
这篇关于不安全上下文中C#中的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!