C#与dll互操作

时间:2010-04-06 16:59:06

标签: c# interop

使用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#中

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;

那么我做错了什么? 吉姆

1 个答案:

答案 0 :(得分:0)

CharSet = CharSet.Ansi -

否则将Unicode传递到您的库

你确定#1?

修改

interop bible是adam nathans book .net and com:完整的互操作性指南