473,756 Members | 3,566 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to pass array of structures into a C dll with PInvoke?

Hello :)

I have a DLL file written in C where one function accepts an array of
structures as input paramter and pointer to length integer.
This function will fill up the array and specify the number of items set.
In other words the prototype looks like: void Func(mystruct *pStruct, int
*npLength);

I would like to call this from C# but I'm having a lot of trouble getting it
to accept this array as parameter.

I mapped my structure into a C# class:

[StructLayout(La youtKind.Sequen tial, CharSet = CharSet.Ansi)]
public class Host
{
public HOST_TYPES nHostType;

// char * string of length MAX_SHORT_STRIN G_LENGTH
[MarshalAs(Unman agedType.LPStr, SizeConst = MAX_SHORT_STRIN G_LENGTH)]
public String strDescription;

// unsigned char array of length MAX_SHORT_STRIN G_LENGTH
[MarshalAs(Unman agedType.U1, SizeConst = MAX_SHORT_STRIN G_LENGTH)]
public byte [] sValue;

public int nLength;

[MarshalAs(Unman agedType.LPStr, SizeConst = MAX_SHORT_STRIN G_LENGTH)]
public String strStringValue;
}

Then I made a prototype in C# for my function:

[DllImport("mydl l.dll", CharSet=CharSet .Ansi, EntryPoint = "#14")]
private static extern ERRORCODES CSHost(IntPtr Handle, HOST_TYPES nHostType,
[MarshalAs(Unman agedType.LPArra y)] Host [] lpHost, ref int nHost);

By doing printouts from my C function I can see that all parameters except
Host [] gets mapped like they should.
For testing I tried to make an array and set the first member but still it
prints out garbage from inside the DLL. Similarly when I try to fill the
first member of the array with data it causes the program to crash with an
exception.

Inside C# the array is initialized like this:

lpHost = new Host[MAX_HOSTS];

for (int i = 0; i < lpHost.Length; i++)
lpHost[i] = new Host();

What am I missing here? I tried lots of combinations of keywords including:
ref and [In,Out]

Thanks in advance.

-- John
Nov 16 '05 #1
2 3564
John,
[StructLayout(La youtKind.Sequen tial, CharSet = CharSet.Ansi)]
public class Host


Try making Host a struct.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 16 '05 #2
> >[StructLayout(La youtKind.Sequen tial, CharSet = CharSet.Ansi)]
public class Host


Try making Host a struct.


Thanks alot! :)

I should have asked earlier since it did the trick. I naturally found out
afterwards I had more bugs with the marshalling but now it's working like
it's suppose to.

However theres one thing I don't quite understand.

To make it work I have to convert the type:
char szDescription[MAX_SHORT_STRIN G_LENGTH];
to
[MarshalAs(Unman agedType.ByValT Str, SizeConst = MAX_SHORT_STRIN G_LENGTH+1)]
public String strDescription;

What annoys me is the "+1" in the size which I didn't find any clear answer
for. The best guess I have is something like the zero termination, which is
about the only explanation I can think of. Any of you know more?

Thanks in advance.
-- John
Nov 16 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1786
by: jrefactors | last post by:
In the following program, are parameters s in function reverse() and x in function count() both pass by value? How come value k is not changed, but value str has changed? Please advise. thanks!! ============================================ void reverse(char s); void count(int x);
4
7296
by: emma middlebrook | last post by:
Hi Straight to the point - I don't understand why System.Array derives from IList (given the methods/properties actually on IList). When designing an interface you specify a contract. Deriving from an interface and only implementing some of it means something is wrong: either the interface specification is wrong e.g. not minimal or the derivation is wrong e.g. the type can't actually honour this contract.
16
14136
by: Ekim | last post by:
hello, I'm allocating a byte-Array in C# with byte byteArray = new byte; Now I want to pass this byte-Array to a managed C++-function by reference, so that I'm able to change the content of the byteArray and afterwards see the changes in C#. (if you wanna know more details: the goal is to write the content of an existing char-array in c++ precisely into the passed byteArray, so that after the function has proceded the content of the...
6
2262
by: Mythran | last post by:
struct MyStruct { public int Number; } struct MyStruct { private int mNumber; public int Number
6
1726
by: Boni | last post by:
Dear all, I have written a C++ COM object: STDMETHOD(myfunc)(INT* array) Now I need to pass an array from c# to COM. I generated a COM interop and the signature of the function is myfunc(ref int)
1
2555
by: Scott McFadden | last post by:
What is the proper way to pass pointers by reference from managed c++ calls to native c++ calls? In managed C++, I have a pointer to an array of structures, that I pass to a native c++ method by reference: //Managed c++ QueryResult* qr = NULL; ExecuteQuery(1, "abc", qr); //invoke native c++ method passing qr by reference
0
986
by: srinivas | last post by:
Hi , Pls help me to solve this problem . /* --this is one of the function in COM component */ int ProjectLIsts(LPCTSTR prj , VARIANT* prj_list) { prj_Lists= { ARRY OF STRUCTURES . ,.ONE STRUCTERES FOR EACH PROJECT
44
5801
by: svata | last post by:
Hello, I wonder how to resize such array of structures using realloc()? #include <stdio.h> #include <stdlib.h> #define FIRST 7 typedef struct { char *name;
4
8104
by: robert.waters | last post by:
I have to parse a binary file having a number of fixed records, each record containing datas in fixed positions. I would like to parse this binary file into an array of structures having members that represent those fields, so that I can access the records in a meaningful way. Using C, I would have defined a struct that I could cast a byte array into, which held exactly one of these fixed records. The struct would be defined as such:...
0
9456
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9275
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10034
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9872
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9843
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9713
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8713
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6534
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5304
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.