tags:

views:

108

answers:

3

Hello, I'm having a hard time with a project (in c++.net) that needs to be converted to c#. This project uses an API written in unmanaged c++. I have the API´s .lib, .dll and .h, and want to call the dll functions from inside .net using p/invoke. Ok, here's the code: First, there is this c++ struct

typedef struct {
    struct Item {
        int  condition;
        char name[80];

        Item::Item()
        {
            reset();
        }

        void Item::reset()
        {
            condition = 0;
            memset(name, 0, sizeof(name));
        }
    };

    bool    channel[32];
    int     itemCount;
    Item    item[5];
} TEXTIN_QUERY_CONDITION, *LPTEXTIN_QUERY_CONDITION;

which translated to c# would have been something like this (I guess, correct me if I'm wrong):

[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct TEXTIN_QUERY_CONDITION
{
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValArray, 
    SizeConst = 32, ArraySubType = System.Runtime.InteropServices.UnmanagedType.Bool)]
    public bool[] channel;
    public int itemCount;
    public ItemClass[] item; //how define the size (5)???
}

and my ItemClass looks like this:

class ItemClass
{
    public Item item = new Item();

    [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, 
    CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
    public struct Item
    {
        public int condition;
        [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, 
        SizeConst = 80)]
        public string name;
    }

    public ItemClass()
    {
        reset();
    }

    public void reset()
    {
        item.condition = 0;
        item.name = new string('0', 80);
    }
}

In .h file there's a definition for this function:

bool search_queryTextIn(const LPBYTE condition, bool queryNext);

which I think translates to c# like this:

[DllImport("search.dll")]
protected static extern bool search_queryTextIn( 
    [MarshalAs(UnmanagedType.LPArray)] byte[] condition, 
    [MarshalAs(UnmanagedType.I1)] bool queryNext);

Then, inside the c++ code, the function is called using this:

void queryTextIn(TEXTIN_QUERY_CONDITION& condition, bool queryNext)
{
    _searchCore.queryTextIn(&condition, queryNext);
}

and the _searchCore.queryTextIn method is defined like this:

bool SearchSDK_Class::queryTextIn(const LPTEXTIN_QUERY_CONDITION condition, bool queryNext)
{
    return ::search_queryTextIn((LPBYTE)condition, queryNext);
}

which calls the function defined in .h above. My major problem is how to call this function from c#. First, I created an instance of the TEXTIN_QUERY_CONDITION struct, but I don't know how to pass a pointer to this struct as a parameter, and how convert it to a byte array to finally call the function... Please, please, are there some kind soul that help me figure out that last bit to call the unmanaged function? Thanks a million.

A: 

The item member is not a pointer, so the ItemClass translation needs to be a value type, not a class. Then use the MarshalAs attribute and specify SizeConst just like you did with channel. Or use the fixed keyword.

Ben Voigt
thanks, but if I define ItemClass as a struct, then how do I translate the reset method? Also, what type will be my UnmanagedType? Struct?
What do you mean "translate" the reset method? Just assign `someItem = new Item();` to zero all contents. With the `fixed` keyword, you don't have to specify any `UnmanagedType` enumeration.
Ben Voigt
Ok, I removed the ItemClass class and left only the Item struct. But when I tried public fixed Item item[5]; it says "fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double"
Oh, that's got to be a bug. It ought to be usable with any and all blittable value types. I wish Eric Lippert would come and comment. What if you change the `name` field within item to `fixed byte name[80]`? As a workaround, you could always replace `fixed Item items[5];` by `Item item0, item1, item2, item3, item4;` although that isn't quite so convenient to access.
Ben Voigt
A: 

Well, the only thing that worked for my struct was the following:

[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValArray, 
SizeConst = 5, ArraySubType = System.Runtime.InteropServices.UnmanagedType.Struct)]
public Item[] item;                      

So I'm able to create an instance of TEXTIN_QUERY_CONDITION struct. But now I'm trapped in how to define the c++ function:

bool search_queryTextIn(const LPBYTE condition, bool queryNext);

Currently I have this:

    [DllImport("search.dll")]
    protected static extern bool search_queryTextIn(
        [In,Out] IntPtr condition,
        [MarshalAs(UnmanagedType.I1)] bool queryNext);

and I'm calling that function as:

        TEXTIN_QUERY_CONDITION condition;
        //... here I fill the struct with data...

        IntPtr result = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(HeaderStruct.TEXTIN_QUERY_CONDITION)));
        IntPtr c = new IntPtr(result.ToInt32());
        Marshal.StructureToPtr(condition, c, true);
        c = new IntPtr(c.ToInt32() + Marshal.SizeOf(typeof(HeaderStruct.TEXTIN_QUERY_CONDITION)));
        search_queryTextIn(c ,queryNext); 

Is my approach of using IntPtr correct? Sometimes the unmanaged DLL works, sometimes doesn't. When it works, it returns an IntPtr pointing to another struct. How can I convert this pointer info back to that struct? I'm trying Marshal.PtrToStructure() but no luck, it fills the struct with garbage... Thanks for any help.

A: 

maybe this could be helpful to you :

Implementing an unmanaged C++ interface callback in C#/.Net

rotoglup