不安全上下文中C#中的指针 [英] Pointers in C# in unsafe context

查看:1368
本文介绍了不安全上下文中C#中的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好
我有一个将数据来回传输到第三方软件的项目.通过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.

推荐答案

您好,

我认为这可以解决您的问题.请参阅此页面上的第三个代码示例:
http://msdn.microsoft.com/en-us/library/chfa2zb8 (v = vs.71).aspx [
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:
unsafe
{
    OnNewFrame = new delOnNewFrame(OnNew_Frame);
}



希望这会有所帮助,
Ed



Hope this helps,
Ed


这篇关于不安全上下文中C#中的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆