简体   繁体   English

与dll的C#互操作

[英]C# Interop with dll

Using VS2008 C# am attempting to interop a C++ dll. 使用VS2008 C#尝试互操作C ++ dll。 Have a C++ class constructor: make_summarizer(const char* rdir, const char* lic, const char* key); 有一个C ++类的构造函数:make_summarizer(const char * rdir,const char * lic,const char * key); Need to retain a reference to the object that is created so I can use it in a follow-on function. 需要保留对所创建对象的引用,以便在后续功能中使用它。 When I did this in JNI the c code was: declare a static pointer to the object: static summarizer* summrzr; 当我在JNI中执行此操作时,C代码是:声明指向对象的静态指针:static summaryr * summrzr; Then in one of the functions I called this constructor as follows: summrzr = make_summarizer(crdir, clic, ckey); 然后在其中一个函数中,我按如下方式调用此构造函数:summrzr = make_summarizer(crdir,clic,ckey); Where the parameters all where the requisite const char* type; 其中,所有参数都是必需的const char *类型;

So in C# 所以在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);
        }
    }

Have also tried using IntPtr created using Marshal.StringToHGlobalAnsi(string). 还尝试过使用通过Marshal.StringToHGlobalAnsi(string)创建的IntPtr。 Regardless I get a AccessViolationException on the line where I call the native constructor; 无论如何,我在调用本机构造函数的行上都会得到一个AccessViolationException;

So what am I doing wrong? 那我在做什么错? Jim 吉姆

CharSet = CharSet.Ansi - CharSet = CharSet.Ansi-

otherwise its passing Unicode to your library 否则将Unicode传递到您的库

are you sure about #1? 您确定第一吗?

edit 编辑

the interop bible is adam nathans book .net and com : the complete interoperability guide 互操作性圣经是adam nathans book .net and com:完整的互操作性指南

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM