C# Interop with dll

Posted by Jim Jones on Stack Overflow See other posts from Stack Overflow or by Jim Jones
Published on 2010-04-06T16:59:05Z Indexed on 2010/04/06 18:33 UTC
Read the original article Hit count: 603

Filed under:
|

Using VS2008 C# am attempting to interop a C++ dll. Have a C++ class constructor: 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; Then in one of the functions I called this constructor as follows: summrzr = make_summarizer(crdir, clic, ckey); Where the parameters all where the requisite const char* type;

So in 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). Regardless I get a AccessViolationException on the line where I call the native constructor;

So what am I doing wrong? Jim

© Stack Overflow or respective owner

Related posts about c#

Related posts about interop