Josh
Josh

Reputation: 1052

Accessing pointer parameter values from a C++ DLL in C#

I have this C++ dll with the following function:

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#. Here is the function definition in 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. 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#.

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.

Upvotes: 0

Views: 188

Answers (1)

Dmitry
Dmitry

Reputation: 14059

Try to declare the imported function as:

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

And call it without ref:

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

Upvotes: 2

Related Questions