使用 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/