【问题标题】:How to get refference to the unmanaged (not COM) interface in C#?如何在 C# 中获取对非托管(非 COM)接口的引用?
【发布时间】:2013-03-29 03:19:21
【问题描述】:

我有一个实现一些 API 的本机 DLL。 C++ 标头如下所示:

class CAPIInterface
{
public:
    virtual int    __stdcall Release()=0;
    virtual LPCSTR __stdcall ErrorDescription(const int code)=0;
    virtual int  __stdcall Login(const int login,LPCSTR password)=0;
}

在 C++ 中,以这种方式获取指向接口的指针:

typedef int (*APICreate_t)(int version,CAPIInterface **api);

pfnAPICreate =reinterpret_cast<APICreate_t>(::GetProcAddress(hlib,"APICreate"));
CAPIInterface *api=NULL;
if(pfnAPICreate) (*pfnAPICreate)(version,&api);

接口的方法是这样调用的:

api->Login(123,"password");

现在我需要加载这个原生 DLL 并在我的 C# 程序中使用 API。我设法以这种方式加载 DLL 并获取指向本机接口的指针:

    public static class GlobalMembers
    {
        [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        public delegate int APICreate_t(time_t version, out IntPtr api);
    }
    ptr_pfnAPICreate = NativeMethods.GetProcAddress(hlib,"APICreate");
    pfnAPICreate = (GlobalMembers.APICreate_t)Marshal.GetDelegateForFunctionPointer(ptr_pfnAPICreate, typeof(GlobalMembers.APICreate_t));
    pfnAPICreate(version, out mptr);

但现在我不确定如何将此指针 (mptr) 映射到接口的 C# 实现。另外我也不确定如何在 C# 中声明接口 CAPIInterface。我尝试以这种方式声明接口:

[StructLayout(LayoutKind.Sequential)]
public class CAPIInterface
{
    public delegate int Release();
    public delegate string ErrorDescription(int code);
    public delegate int Login(int login, string password);
}

但是它没有编译......它返回这个错误: 错误 3 不可调用的成员 'CAPIInterface.Login' 不能像方法一样使用。我知道代表也必须在某个地方实例化......但是怎么做呢?如上所述声明 CAPIInterface 是否正确?

【问题讨论】:

  • 你应该试试swig.org/Doc1.3/CSharp.html 这样的方法,这样会更容易
  • 谢谢,但如果可能的话,我宁愿直接从我的 C# 应用程序调用本机 DLL 的方法。你能给我一些建议如何在我的代码中做到这一点吗?
  • 我不知道如何做到这一点,但我想知道让你的 C++ 库 COM 可见并让 C# 使用 COM 代替库不是更容易。
  • 将 C++ 类映射到 C# 不适合胆小的人,除非您使用的是严格的 COM 接口。简单的做法是使用 SWIG 或为 C++ 对象存储 IntPtrs,并使用将 C++ 类指针作为第一个参数的外部 C 函数
  • 我以前从未使用过 SWIG...你能告诉我如何用 SWIG 转换我的 C++ API 标头吗?

标签: c# pointers interface unmanaged


【解决方案1】:

在 SWIG 的帮助下,我能够将我的 C++ API 转换为 C#。它工作得很好。谢谢。

【讨论】:

  • 你能解释一下你是怎么做到的吗?
猜你喜欢
  • 2013-04-28
  • 2011-01-10
  • 1970-01-01
  • 1970-01-01
  • 2012-09-23
  • 2010-10-25
  • 2020-05-03
  • 2012-02-13
  • 2011-10-14
相关资源
最近更新 更多