[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2006-11-02
9
Medium Priority
?
757 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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 2000 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses
Course of the Month18 days, 1 hour left to enroll

831 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