C# 与 dll 互操作

标签 c# interop

使用 VS2008 C# 我正在尝试互操作 C++ dll。 有一个 C++ 类构造函数: make_summarizer(const char* rdir, const char* lic, const char* key); 需要保留对创建的对象的引用,以便我可以在后续函数中使用它。 当我在 JNI 中这样做时,c 代码是: 声明一个指向对象的静态指针: 静态汇总器* summrzr; 然后在我调用此构造函数的函数之一中,如下所示: summrzr = make_summarizer(crdir, clic, ckey); 其中参数全部是where必需的const char*类型;

所以在 C# 中

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Configuration;

namespace SummarizerApp
{
  class SummApp
  {
    private IntPtr summarzr;

    public SummApp()
    {
        string resource_dir = ConfigurationManager.AppSettings["resource_dir"];
        string license = ConfigurationManager.AppSettings["license"];
        string key = ConfigurationManager.AppSettings["key"];
        createSummarizer(resource_dir, license, key);
    }

    [System.Runtime.InteropServices.DllImportAttribute("lib\\summarizer37.dll", EntryPoint = "#1")]
    public static extern IntPtr make_summarizer(
        [InAttribute()][MarshalAsAttribute(UnmanagedType.LPTStr)] string rdir,
        [InAttribute()][MarshalAsAttribute(UnmanagedType.LPTStr)] string lic,
        [InAttribute()][MarshalAsAttribute(UnmanagedType.LPTStr)] string key);

    public void createSummarizer(string resource_dir, string license, string key)
    {
        try
        {
            this.summarzr = make_summarizer(resource_dir, license, key);
        }
        catch (AccessViolationException e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
        }
    }

还尝试使用通过 Marshal.StringToHGlobalAnsi(string) 创建的 IntPtr。 不管我在调用 native 构造函数的行上遇到 AccessViolationException ;

那我做错了什么? 吉姆

最佳答案

CharSet = CharSet.Ansi-

否则它会将 Unicode 传递给您的图书馆

你确定#1 吗?

编辑

互操作圣经是 adam nathans 的书 .net 和 com:完整的互操作指南

关于C# 与 dll 互操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2586696/

相关文章:

c# - 当我使用 regasm 时,所有参数都输入为输入?那可以改变吗?

c# - 将 C# 方法转换为 C++ 方法

c# - 从网站批量打印存储在服务器上的文件

c# - 我是否需要为抽象类提供一个空的 protected 构造函数?

c# - 依赖注入(inject)

python - 是否有任何项目/库集可以轻松地在各种编程语言/平台之间进行通信?

c# - Ninject - 绑定(bind)类型列表

c# - 需要调用 StreamWriter.Flush() 将字符写入文件?

c# - 在外部应用程序中设置文本框的文本。 Win32 API

c++ - C# 与非托管 C++ 互操作性的续篇