[英]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;
}
}
}
}
它會拋出錯誤指針,固定大小的緩沖區只能在不安全的上下文中使用。 如何將指針傳遞給C ++ DLL? 我是C#的新手,請幫助我
而不是使用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);
撥打電話:
ushort major, minor;
SRX_DllVersion(out major, out minor);
我假設SRX_DllVersion參數僅輸出,如果不改變out
到ref
。
盡可能避免使用unsafe
代碼。
當然,你要標記這個類是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);
}
如果您只有一種方法,則可以將該方法標記為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);
嘗試使用unsafe
阻止。 更多關於不安全的 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.