Jorb
Jorb

Reputation: 153

Pinvoke "System.AccessViolationException" when trying to import unmanaged dll

I am trying to import a driver dll for a piece of equipment my company uses, but I can't seem to get this to work. I am new to c# so please go easy on me. This is related to a post I made yesterday, I am attempting to convert a C program over to C#.

I wrote this code so that I could start to understand PInvoke

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace PInvokeTest {
  class Program {
    static void Main(string[] args) {
        Int32 session_handle = 0;
        Byte state_buffer = 0;
        Int16 result = 1, PortNum = 1, PortType = 1;

        session_handle = TMExtendedStartSession(PortNum, PortType);

        result = TMSearch(session_handle, state_buffer, 1, 1, 0xEC);

        if (result == 1)
            Console.WriteLine("Device Found");

        if (result == -201)
            Console.WriteLine("Hardware Driver Not Found");

        else
            Console.WriteLine("Network Error");



        Console.ReadKey();
    }
    [DllImport("IBFS32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
    public static extern Int32 TMExtendedStartSession(Int16 PortNum, Int16 PortType);

    [DllImport("IBFS32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
    public static extern Int16 TMSearch(Int32 session_handle, Byte state_buffer, int p1, int p2, int p3);  

  }
}

I am trying to use these 2 functions

TMExthendedStartSession http://files.maximintegrated.com/sia_bu/licensed/docs/1-wire_sdk_win/TMEX/exst8l9q.html

and TMSearch http://files.maximintegrated.com/sia_bu/licensed/docs/1-wire_sdk_win/TMEX/sear1ezy.html

When I run TMExthendedStartSession I get System.AccessViolationException, but when I run TMSearch alone I get a message "Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'C:\PInvokeTest\Debug\PInvokeTest.vshost.exe'."

The function TMSearch does return a value of -201 though.

Any help is appreciated.

Upvotes: 0

Views: 1054

Answers (1)

David Heffernan
David Heffernan

Reputation: 612794

In 32 bit Windows, the pascal calling convention maps to stdcall. There is a #define near the top of WinDef.h (or minwindef.h in more modern SDKs) that maps pascal to __stdcall.

On top of that, your parameters are all wrong. It should be like this:

[DllImport("IBFS32.dll")]
public static extern int TMExtendedStartSession(
    short PortNum, 
    short PortType,
    IntPtr EnhancedOptions 
);

[DllImport("IBFS32.dll")]
public static extern short TMSearch(
    int session_handle, 
    IntPtr state_buffer, 
    short p1, 
    short p2, 
    short p3
);  

The state_buffer parameter might perhaps be better declared as byte[]. It's hard to tell from here what the semantics are.

Upvotes: 1

Related Questions