tags:

views:

105

answers:

1

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

A: 

CharSet = CharSet.Ansi -

otherwise its passing Unicode to your library

are you sure about #1?

edit

the interop bible is adam nathans book .net and com : the complete interoperability guide

pm100
OK set the CharSet value as above. Checked the ordinal base and it turned out to be #4. Now I get the dialog that says: "Runtime Error!" New error = progress I always say, Thanks
Jim Jones
why have it at all (#n) - why not let the name do the work for you
pm100
i also think that LPStr is the correct type not LPCTstr
pm100
The name is decorated
Jim Jones
The use of LPStr vs LPTStr was the final answer, Thanks. Now tell me where I can get the information that would allow me to figure this out for myself?Jim
Jim Jones
@pm100: CharSet.Ansi is the default if you don't specify something else.
Mattias S