5
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# 新手,请帮助我

4

4 回答 4

8

而不是使用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使用代码。

于 2013-10-18T19:22:34.553 回答
3

当然,您必须标记课程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.

并且不要忘记打开“允许不安全代码”编译器选项。

于 2013-10-18T19:20:11.080 回答
1

您必须将该方法标记为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);
于 2013-10-18T19:17:54.190 回答
0

尝试使用unsafe块。更多关于unsafe

于 2013-10-18T19:23:03.480 回答