Solved

questing about porting C to C#, dllimport, and probably something about marshalling

Posted on 2006-11-02
9
742 Views
Last Modified: 2011-04-14
Hey folks,

Here's the situation. I've got a C dll, and I want to call the functions in it from a C# app. I can call these functions, but they don't behave the same when called from a C# program as they do when called from a C app. I'm having a problem with one in particular, PeekRequest(). Here's how its called in the C program:

int set_channel( int channel )
{
    unsigned long reqdata[139];
    OVERLAPPED iodata;

    memset( (void *) reqdata, 0, sizeof( reqdata ) );
    memset( (void *) &iodata, 0, sizeof(  iodata ) );

    iodata.hEvent = CreateEvent( 0, 0, 0, 0 );

    reqdata[5] = 1;
    reqdata[6] = 0xFF636713;
    reqdata[7] = (unsigned long) &channel;
    reqdata[8] = 4;

    return( PeekRequest( hAdapter, reqdata, &iodata ) );
}

The prototype of this function is:
 HANDLE PeekRequest(HANDLE,void *,OVERLAPPED);

Here's the same function in my C# program. I first import the dll with:

[DllImport("Peek.dll")]
            public static extern IntPtr PeekRequest
      (IntPtr netcrudAdapter,
       uint[] reqdata,
       System.Threading.NativeOverlapped iodata);

and import the CreateEvent function:

    //Win32 API call for which no C# equivalent exists        
    [DllImport("kernel32.dll", SetLastError=true)]
    static extern IntPtr CreateEvent(IntPtr lpEventAttributes,
    bool bManualReset, bool bInitialState,
    [MarshalAs(UnmanagedType.LPStr)] String lpName);


private long set_channel(uint channel)
            {
            //array of unsigned integers
            uint[] reqdata = new uint[139];
           
            //C# version of OVERLAPPED type
            System.Threading.NativeOverlapped iodata;

            //Initialize array
            for (int i = 0; i < 139; i++)
              reqdata[i] = 0;
           
            //TODO - may need to initialize iodata
            iodata.EventHandle = IntPtr.Zero;
            iodata.InternalHigh = IntPtr.Zero;
            iodata.InternalLow = IntPtr.Zero;
            iodata.OffsetHigh = 0;
            iodata.OffsetLow = 0;

            iodata.EventHandle = CreateEvent(IntPtr.Zero, false, false, string.Empty);

            reqdata[5] = 1;
            reqdata[6] = 0xFF636713;
            reqdata[7] = (uint)&channel;
            reqdata[8] = 4;

            return((long)PeekRequest(netcrudAdapter, reqdata, iodata));
            }


Still with me? Excellent. So here's the meat of the problem. The C function returns 0 for a given channel, which is good. The same function in C# returns 87, which is garbage. Any advice?

Much thanks,
Nathan King
   
0
Comment
Question by:quadrille01
  • 5
  • 3
9 Comments
 
LVL 10

Expert Comment

by:anv
ID: 17864287
Hi Nathan,

How about using reflection in this case?

--anv
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 17864381
Before learning this PInvoke stuff, I want to ask general question: why don't you use C++/CLI for this? If you know both C and C#, you can easily do this with C++/CLI instead of writing these ugly PInvoke declarations.
Advantage of C++/CLI is that it allows to call unmanaged functions directly from managed code. You need to write wrapper C++/CLI class library which exposes pure managed interface to C# client, and internally calls unmanaged functions.
If you don't want to work with C++/CLI, I will try to find the problem in this code.
0
 

Author Comment

by:quadrille01
ID: 17864600
Why use all C#? Well, the biggest reason is that it seemed like a good idea at the time. And now that I've spent this much time on it I'd like to just keep on this path if I can. There are a couple functions from this dll that behave using PInvoke declarations. I suspect my problem is mismatching my managed and unmanaged types when going from C to C#.

I'm certainly not averse to switching to C++/CLI if thats what it comes to.

Nathan
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 17864696
Well, let's look at PInvoke stuff.

static extern IntPtr CreateEvent(IntPtr lpEventAttributes,
    bool bManualReset, bool bInitialState,
    [MarshalAs(UnmanagedType.LPStr)] String lpName);

bool parameters don't match BOOL type - change to int.
Replace last parameter type with IntPtr and pass IntPtr.Zero.

reqdata[7] = (uint)&channel;
Allocate ubnmanaged memory block using Marshal.AllocHGlobal, copy channel value to it using Marshal.WriteInt32. Marshal.AllocHGlobal returns IntPtr. Convert it to int using ToInt32 method, and assign to reqdata[7]. Notice that C# long is 64-bits value. I guess that PeekRequest excpects 32 bits, replace with int.

C# PeekRequest definition.
Replace reqdata parameter type with IntPtr. Allocate unmanaged memory block using Marshal.AllocHGlobal, fill it using Marshal.Copy.

return((long)PeekRequest(netcrudAdapter, reqdata, iodata));

Replace return value with IntPtr.ToInt32.

If you have PeekRequest source code, debug it to see parameter values.

PInvoke sucks (side note).
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 

Author Comment

by:quadrille01
ID: 17872035
Hey, thanks for the reply.

I've changed most of what you suggested. I can't allocate reqdata using Marshal.AllocHGlobal, since I need an unsigned int for element 6. Is there an unsigned equivalent?

"If you have PeekRequest source code, debug it to see parameter values."
Would that I did, my friend.

"PInvoke sucks (side note)."
Yeah, I'm getting that. I'm a hair's breadth from the more-trouble-than-its-worth stage. It may be time go ahead and switch over to C++/CLI for handling the dll functions.
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 17872251
If you can debug PeekRequest, you can see what parameters are wrong.

I give you short translation of most tricky part, I hope this can give you idea how to prepare unmanaged memory for API. Managed data is kept in manaded memory. Unmanaged data for API should be marshaled to unmanaged memory. For simple parameters like int, char, string, PInvoke generates default marshalling. We need only declare function prototype correctly. For non-trivial parameters we can allocate unmanaged memory blocks and fill them using Marshal functions. They have all we need, every C++ programmer can use them.

int set_channel( int channel )
{
    unsigned long reqdata[139];   // we use int for this - the same size
    reqdata[5] = 1;
    reqdata[6] = 0xFF636713;
    reqdata[7] = (unsigned long) &channel;
    reqdata[8] = 4;

    PeekRequest( ..., reqdata, ...) );   // declare reqdata as IntPtr for C#
}

IntPtr channelPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)));
Marshal.WriteInt32(channelPtr, channel);   // channel in unmanaged memory

IntPtr reqdata = Marhal.AllocHGlobal(Marshal.SizeOf(typeof(int)), 139);
Marhal.WriteInt32(reqdata, 5, 1);
Marhal.WriteInt32(reqdata, 6, 0xFF636713);   // will be OK
Marshal.WriteInt32(reqdata, 7, channelPtr.ToInt32());   // write pointer to channel in unmanaged memory
Marhal.WriteInt32(reqdata, 8, 4);

PeekRequest( ..., reqdata, ...) );  
// read output if required
Marhal.FreeHGlobal(channelPtr);
Marhal.FreeHGlobal(reqdata);

I think that System.Threading.NativeOverlapped iodata parameter must be passed as ref. By default structure it is marshalled by value.
0
 
LVL 48

Accepted Solution

by:
AlexFM earned 500 total points
ID: 17872260
>> It may be time go ahead and switch over to C++/CLI for handling the dll functions.
If this is last unmanaged API that you need, I beleive you can stay with C#. If you need to write a lot if interoperability code, use C++/CLI. Actually, C++/CLI is done exactly for this, there is no other reason to use it.
0
 

Author Comment

by:quadrille01
ID: 17875297
Thanks Alex, I imagine I can take it from here. I've got to switch to C++/CLI, if for no other reason than that there appears to be no mechanism for writing an unsigned int into unmanaged memory. I've tried a hundred different ways of doing

Marhal.WriteInt32(reqdata, 6, 0xFF636713);

but the compiler says no.

Thanks again.
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 17875884
Marshal.WriteInt32(reqdata, 6, unchecked((int)0xFF636713));
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now