C Structure

G

Guest

Good Day All,

I have a C function I am trying to call from C# using DLL Import. The
definition for the function is:

int IAListNext(hIAClient, dwHandle, lpData, iMaxLen, lpdwLen)

What has me confused is the ldData parameter. It is of type char FAR *. In
the documentation (which was originall written for the C and VB 6 programmer)
if further defines the parameter as follows:

For C, a pointer to location where the function returns the information for
the
next item in the list.
For VB, a data structure containing an ID of type Long and a Name of type
String having sufficient size to hold all the values that will be returned
to the
list.

I have tired passing a StringBuilder but that did not work. I have also
tried passing, by ref, the following structure:

public struct IATaskListRecord
{

public int ID;
public string Name;

}

But that did not work either. I get a NullReference Exception.

Does anyone have any idea how I should deal with this. I am at a loss.

Thanks!

Dan
 
G

Guest

Dan said:
Good Day All,

I have a C function I am trying to call from C# using DLL Import. The
definition for the function is:

int IAListNext(hIAClient, dwHandle, lpData, iMaxLen, lpdwLen)
<snip>

It depends on how this string is supposed to work.

If the string in the struct is a pointer to where the string is located,
this would do:

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct SomeStruct
{
public Int32 ID;

[MarshalAs(UnmanagedType.LPStr)]
public StringBuilder Text;
}

however, when using it, you need to:

SomeStruct ss = new SomeStruct();
ss.Text = new StringBuilder(1000); // make 1000 big enough
IAListNext(..., ref ss, ...)

If, on the other hand, the string is defined as a character array in the
struct, this would do:

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct SomeStruct
{
public Int32 ID;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst=1000)]
public StringBuilder Text;
}

Note the following:
CharSet=CharSet.Ansi <-- 8-bit characters
CharSet=CharSet.Unicode <-- Text is unicode
SizeConst=1000 <-- number of characters, not bytes

The definition of your IAListNext method would be:

[DllImport("Yourdll.dll")]
public static extern Int32 IAListNext(
IntPtr hIAClient,
Int32 dwHandle,
ref SomeStruct lpData,
Int32 iMaxLen,
Int32 lpdwLen);

The rules for String vs. StringBuilder is:

[in]: String
[out]: StringBuilder
[in/out]: StringBuilder

in --> pass data to method
out --> method changes data before returning

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top