[英]How to access a C++ function which takes pointers as input argument from a C#
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?
如何将指针传递给C ++ DLL? I am new to C#, please help me
我是C#的新手,请帮助我
Rather than using an unsafe
context try: 而不是使用
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);
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
. 我假设SRX_DllVersion参数仅输出,如果不改变
out
到ref
。
Avoid unsafe
code when ever possible. 尽可能避免使用
unsafe
代码。
Of course you've to mark the class unsafe
to make it work. 当然,你要标记这个类是
unsafe
,以使它工作。
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
. 如果您只有一种方法,则可以将该方法标记为
unsafe
。
And don't forget to turn on "allow unsafe code" compiler option as well. 并且不要忘记打开“允许不安全的代码”编译器选项。
You must mark that method as unsafe
您必须将该方法标记为
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.