简体   繁体   English

从C#中的C ++ DLL访问指针参数值

[英]Accessing pointer parameter values from a C++ DLL in C#

I have this C++ dll with the following function: 我有以下功能的C ++ dll:

extern "C" INT16 WINAPI SetWatchElements(INT16 *WatchElements)
{
INT16 Counter;

//some code

for (Counter = 0; Counter < WATCHSIZE; Counter++)
    WatchElements[Counter] = MAPINT(WatchData[Counter]);

//some code

return ReturnValue;
}

Essentially it just assigns some values to the pointer/array that is passed in. 本质上,它只是将一些值分配给传入的指针/数组。

My problem arises when I attempt to call this function via C#. 当我尝试通过C#调用此函数时,出现了我的问题。 Here is the function definition in C#: 这是C#中的函数定义:

[DLLImport("MyDll.dll")]
private static extern int SetWatchElements(ref Int16 watchElements);

and how I am calling it: 以及我怎么称呼它:

Int16 someData = 0;
var result = SetWatchElements(ref someData);

This compiles fine and my variable someData actually has a value in it that is right. 这样编译就可以了,我的变量someData实际上有一个正确的值。 The problem is that since in C++ world the values are set beyond the realm of a single value so I am unsure how to access that in C#. 问题在于,由于在C ++世界中,这些值的设置超出了单个值的范围,因此我不确定如何在C#中访问它。

I've tried doing something like this: 我尝试做这样的事情:

Int16[] someData = new Int16[80];
var result = SetWatchElements(ref someData[0]);

but the result is the same. 但结果是一样的。

PS: I CANNOT use unsafe here as it is against our standards. PS:我不能在这里使用不安全的东西,因为这违反了我们的标准。

Try to declare the imported function as: 尝试将导入的函数声明为:

[DLLImport("MyDll.dll")]
private static extern int SetWatchElements(Int16[] watchElements);

And call it without ref : 并在没有ref情况下调用它:

Int16[] someData = new Int16[80];
var result = SetWatchElements(someData);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM