簡體   English   中英

如何訪問C#函數,它將指針作為C#的輸入參數

[英]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參數僅輸出,如果不改變outref

盡可能避免使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM