473,772 Members | 2,513 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

problem dllImport struct array

1 New Member
Hi,

I want to use an unmanaged dll in C# .net and I'm having some troubles witch a function that should return an array. I'm new at this, so I don't know what I'm doing wrong.

Here is some code:


#define USERINT_FUNC __cdecl
#ifdef __cplusplus
extern "C" {
#endif
bool __cdecl CCInit();
int __cdecl CCStartScan();
int __cdeclC CCStopScan();
int __cdecl CCGetAllDevsByA rray(DevDataRec ord *dda, int maxDevices);
#ifdef __cplusplus
}
#endif

struct __declspec(dlle xport) DevDataRecord
{
unsigned long snr; // @field unsigned long
char name[256]; // @field char[256]
int dhcp; // @field int
char ip[24]; // @field char[24]
char netmask[24]; // @field char[24]
char gateway[24]; // @field char[24]
int signature; // @field int
char targetname[256]; // @field char[256]
char id[24]; // @field char[24]
int devindex; // @field int
int devmhomeidx; // @field int
char version[24]; // @field char[24]
char model[24]; // @field char[24]
char bootloaderversi on[24]; // @field char[24]
char hwrevision[24]; // @field char[24]
int devicetype; // @field int
char physicaladdress[24]; // @field char[24]
char bname[256]; // @field char[256]
unsigned long bsnr; // @field unsigned long
char bhwrevision[24]; // @field cahr[24]
int dataFlags; // @field int
};


/*************** *************** *************** **************/

This is some test code in Microsoft Visual C++ 6.0. This works fine. The function returns the right devCount and the gDdr array is filled correctly.

#define MAX_DEVICE_COUN T 100
DevDataRecord gDdr[MAX_DEVICE_COUN T];

...

memset(gDdr, 0, sizeof(gDdr) );
int devCount = CCGetAllDevsByA rray(gDdr, MAX_DEVICE_COUN T);


/*************** *************** *************** **************/

Then I started a C# console application in visual studio 2008. I made a Class that calls the functions from the unmannaged dll.

class Caller
{

#region Dll Imports

[DllImport(@"C:\ Temp\ChipContro l.dll", SetLastError = true)]
static extern bool CCInit();
[DllImport(@"C:\ Temp\ChipContro l.dll", SetLastError = true)]
static extern int CCStartScan();
[DllImport(@"C:\ Temp\ChipContro l.dll", SetLastError = true)]
static extern int CCStopScan();
[DllImport(@"C:\ Temp\ChipContro l.dll", SetLastError = true)]
static extern int CCGetAllDevsByA rray([Out]out DevDataRecord ptr, int maxDevices);


[StructLayout(La youtKind.Sequen tial, CharSet = CharSet.Ansi)]
public struct DevDataRecord
{
public UInt32 snr; // @field unsigned long
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 256)]
public string name; // @field char[256]
public int dhcp; // @field int
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 24)]
public string ip; // @field char[24]
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 24)]
public string netmask; // @field char[24]
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 24)]
public string gateway; // @field char[24]
public int signature; // @field int
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 256)]
public string targetname; // @field char[256]
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 24)]
public string id; // @field char[24]
public int devindex; // @field int
public int devmhomeidx; // @field int
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 24)]
public string version; // @field char[24]
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 24)]
public string model; // @field char[24]
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 24)]
public string bootloaderversi on; // @field char[24]
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 24)]
public string hwrevision; // @field char[24]
public int devicetype; // @field int
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 24)]
public string physicaladdress ; // @field char[24]
[MarshalAs(Unman agedType.ByValT Str, SizeConst = 256)]
public string bname; // @field char[256]
public ulong bsnr; // @field unsigned long
[MarshalAs(Unman agedType.ByValA rray, SizeConst = 24)]
public char[] bhwrevision; // @field char[24]
public int dataFlags; // @field int
};

#endregion

public const int MAX_DEVICE_COUN T = 100;
public DevDataRecord[] gDdr;


public Caller()
{
gDdr = new DevDataRecord[MAX_DEVICE_COUN T];
}
public void Init()
{
CCInit();
}
public void StartScan()
{
CCStartScan();
}
public void StopScan()
{
CCStopScan();
}


When I call the function like following, it returns the correct integer, but only the first element of the array is filled. This is the only way to get some result.

public int GetAllDevsByArr ay()
{
try
{
return CCGetAllDevsByA rray(out gDdr[0], MAX_DEVICE_COUN T);
}
catch (Exception e)
{
return 0;
}
}
}

I've tried a lot of other ways that I found in several forums or sites, but none of them work.

Here are some of the other ways:

-----------------------------------------------------------------------------------

static extern int CCGetAllDevsByA rray([Out]out DevDataRecord[] ptr, int maxDevices);
public int GetAllDevsByArr ay()
{
try
{
return CCGetAllDevsByA rray(out gDdr, MAX_DEVICE_COUN T);
}
catch (Exception e)
{
return 0;
}
}
}
-------------------------------------------------------------------------------------
[DllImport(@"C:\ Temp\ChipContro l.dll", SetLastError = true)]
static extern int CCGetAllDevsByA rray(ref DevDataRecord ptr, int maxDevices);
public int GetAllDevsByArr ay()
{
try
{
return CCGetAllDevsByA rray(ref gDdr[0], MAX_DEVICE_COUN T);
}
catch (Exception e)
{
return 0;
}
}
-------------------------------------------------------------------------------------
[DllImport(@"C:\ Temp\ChipContro l.dll", SetLastError = true)]
static extern int CCGetAllDevsByA rray(ref IntrPtr data, int maxDevices);
public int GetAllDevsByArr ay(int maxDevices)
{
try
{
unsafe
{
fixed (IntPtr ptr = gDdr)
{
return CCGetAllDevsByA rray(ptr, maxDevices);
}
}
}
catch (Exception e)
{
return 0;
}
}
-------------------------------------------------------------------------------------
[DllImport(@"C:\ Temp\ChipContro l.dll", SetLastError = true)]
static extern int CCGetAllDevsByA rray(ref Intptr data, int maxDevices);
public int GetAllDevsByArr ay(int maxDevices)
{
try
{
int arrayLen = gDdr.Length;
int structSize = Marshal.SizeOf( typeof(DevDataR ecord));
IntPtr ptr = Marshal.AllocCo TaskMem(arrayLe n * structSize);
for (int i = 0; i < arrayLen; i++)
{
Marshal.Structu reToPtr(gDdr[i], (IntPtr)(ptr.To Int32() + i * structSize), false);
}
int nrDevs = CCGetAllDevsByA rray(ref ptr, maxDevices);
for (int i = 0; i < gDdr.Length; i++)
{
gDdr[i] = (DevDataRecord) Marshal.PtrToSt ructure(ptr, typeof(DevDataR ecord));
ptr = (IntPtr)((int)p tr + Marshal.SizeOf( typeof(DevDataR ecord)));
}
return nrDevs;
}
catch (Exception e)
{
return 0;
}
}

Is there someone who can help me and tell me what I'm doing wrong?
Many thanks,

Elke
Mar 25 '09 #1
1 5799
tlhintoq
3,525 Recognized Expert Specialist
TIP: When you are writing your question, there is a button on the tool bar that wraps the [code] tags around your copy/pasted code. It helps a bunch. Its the button with a '#' on it. More on tags. They're cool. Check'em out.
Mar 25 '09 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

3
4146
by: Schorschi | last post by:
Can someone please point out why I am getting an 87 error? I am sure it is obvious, but I am new to C# and seem to be having a lot of stress understanding managed versus unmanaged code when API calls are needed! // using System; using System.Runtime.InteropServices;
1
3305
by: Keltus | last post by:
Hi, I am trying to write a C# wrapper class for the famous mp3 decoder mpg123. I have gotten the win32 .dll version of it, and have a sample C program that uses the .dll which I think is pretty good. I have not found a C# or even a C/C++ wrapper class of mpglib.dll so this might be a difficult task since mpglib.dll only decodes the .mp3 files to PCM format. The first thing I need to do is use DllImport to import the library
15
4468
by: Jim | last post by:
I am extremely frustrated. I am building c# application for a call center and am using a third party API to access some hardware. When develop and test my class using the windows console the application runs flawlessly, but once I call the class from inside a c# windows application the program freezes, crashes etc... there must be a way to make this work inside a windows app as it run great as a command line app.
4
1413
by: Dirk Reske | last post by:
Hello, I've importet following struct typedef struct { DWORD cbStruct; DWORD fdwStatus; DWORD_PTR dwUser; LPBYTE pbSrc; DWORD cbSrcLength; DWORD cbSrcLengthUsed;
3
4738
by: Webdiyer | last post by:
I want to integrate SecurID two-factor authentication system of the RSASecurity.inc into our asp.net application,but I get into trouble when trying to call the API functions of the ACE Agent,I got an error message saying "Cannot marshal parameter #2: Invalid managed/unmanaged type combination (this value type must be paired with Struct)" when calling "AceGetPinParams(iHandle,ref sd_pin)" function,here's my test code: private static...
3
3315
by: Mohammad-Reza | last post by:
Hi everybody I want to shutdown my computer with my program. I searched in MSDN to find a .NET method that can do that but did'nt find anything but ExitWindowsEx Api. I write following codes to execute this api but every time i use it, I see an error message. Error:1314 " A required privilege is not held by the client. ". Please tell me what did I wrong. Thanks in advance.
1
4560
by: Don.Leri | last post by:
Hi, I have a logger.dll (unmanaged c++ dll compiled in vs2005). I have a C# interop to use that dll in managed code implemented in Interfaces.dll (used by other C# dlls). I also have a number of other C# dlls referencing Interfaces.dll and using logger.dll interop for logging.
6
3271
by: per9000 | last post by:
An interesting/annoying problem. I created a small example to provoke an exception I keep getting. Basically I have a C-struct (Container) with a function-pointer in it. I perform repeated calls to the function in the container. I allocate (and free in c) arrays to get garbage collection in both C and C#. After a few seconds I get an exception. I assume GarbageCollector moves the delegate (or collects is) and when I don't find it in C...
8
2935
by: =?Utf-8?B?UHVjY2E=?= | last post by:
Hi, I'm using vs2005, .net 2, C# for Windows application. I use DllImport so I can call up a function written in C++ as unmanaged code and compiled as a dll us vs2005. My application is able to call the function, EncodeAsnUser. And it's returning OK but when I display the decoded data in another part of my application it shows no data has been decoded, all fiedls are either null or blanks. For some reason, I am not able to step through...
0
9621
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
10264
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
10106
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...
0
9914
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
8937
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...
1
7461
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6716
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
5484
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2851
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.