C#与DLL的互操作
问题描述:
使用VS2008的C# 正试图互操作C++的DLL。 有一个C++类的构造函数: make_summarizer(const char * rdir,const char * lic,const char * key); 需要保留对创建对象的引用,以便我可以在后续功能中使用它。 当我在JNI中这样做时,c代码是: 声明一个指向对象的静态指针: static summarizer * summrzr; 然后在我称之为构造函数的函数之一中,如下所示: summrzr = make_summarizer(crdir,clic,ckey); 凡凡参数凡是必需的const char *类型;因此,在C#C#与DLL的互操作
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(串)的IntPtr创建尝试。 无论我在调用本地构造函数的行上遇到AccessViolationException;
那么我做错了什么? 吉姆
答
字符集= CharSet.Ansi -
否则其传递的Unicode到库
你确定#1?
编辑
互操作的圣经是亚当内森斯书.NET和COM:完全的互操作性指南
确定将charset值如上。检查了序数基地,结果是#4。现在我得到一个对话框:“运行时错误!”新的错误=进步我总是说,谢谢 – 2010-04-06 19:27:12
为什么没有它(#n) - 为什么不让名字为你工作 – pm100 2010-04-06 21:27:59
我也认为LPStr是正确的类型不是LPCTstr – pm100 2010-04-06 21:31:45