using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace PatternSequencer
{
class Version
{
public string majorVersion;
public string minorVersion;
ushort* pmajorVersion;
ushort* pminorVersion;
ulong status;
[DllImport(@"c:\DOcuments\Myapp.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "SRX_DllVersion")]
public static extern ulong SRX_DllVersion(ushort* pmajorVersion, ushort* pminorVersion);
public Version()
{
status = SRX_DllVersion(&pmajorVersion, &pminorVersion);
if (status)
{
majorVersion = "1 - " + *pmajorVersion;
minorVersion = "1 - " + *pminorVersion;
}
else
{
majorVersion = "0 - " + *pmajorVersion;
minorVersion = "0 - " + *pminorVersion;
}
}
}
}
It throws an Error Pointers and fixed size buffers may only be used in an unsafe context. How do I pass pointers to the C++ dll? I am new to C#, please help me
To pass the value by pointer, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to by its arguments.
Just like any other argument, pointers can also be passed to a function as an argument.
Example 2: Passing Pointers to Functions Here, the value stored at p , *p , is 10 initially. We then passed the pointer p to the addOne() function. The ptr pointer gets this address in the addOne() function. Inside the function, we increased the value stored at ptr by 1 using (*ptr)++; .
Rather than using an unsafe
context try:
[DllImport(@"c:\FreeStyleBuild\BERTScope\Release\Bin\BitAlyzerDLL.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "SRX_DllVersion")]
public static extern ulong SRX_DllVersion(out ushort pmajorVersion, out ushort pminorVersion);
To make the call:
ushort major, minor;
SRX_DllVersion(out major, out minor);
I'm assuming the SRX_DllVersion parameters are output only, if not change out
to ref
.
Avoid unsafe
code when ever possible.
Of course you've to mark the class unsafe
to make it work.
unsafe class Version
{
[DllImport(@"c:\FreeStyleBuild\BERTScope\Release\Bin\BitAlyzerDLL.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "SRX_DllVersion")]
public static extern ulong SRX_DllVersion(ushort* pmajorVersion, ushort* pminorVersion);
}
If you have only one method you could mark the method as unsafe
.
And don't forget to turn on "allow unsafe code" compiler option as well.
You must mark that method as unsafe
[DllImport(@"c:\FreeStyleBuild\BERTScope\Release\Bin\BitAlyzerDLL.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "SRX_DllVersion")]
public static extern ulong SRX_DllVersion(out ushort pmajorVersion, out ushort pminorVersion);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With