Solved

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

Posted on 2006-11-02
9
746 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
ScreenConnect 6.0 Free Trial

Explore all the enhancements in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

 
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
 

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

Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…

773 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