Click here to Skip to main content
14,423,094 members

How do I use C dlls in C#?

Meb56 asked:

Open original thread
I developed a dll for specific calculations with matlab and compiled it with mcc.
One of the dlls functions uses pointer to records as result types. This works fine with delphi/pascal constructing records with the same field types as used in the C-Code of the dll. For the dll interface, I use pointer to this record types.

C inplementation of my result record
struct TRecordField {
        char Key[100];    
        byte TypID;          
        int ElemSize;       
        int Rows, Cols;     
        void *Buffer;

Now I try to use the same dll in C#. The address of my result records is given to the dll function getResults with the & Operator, like in the code snippet beneath.
Only the char array 'Key' (represented as byte array in C#) of the records is correct filled after the dll call, numbers (of type int or byte) are always zero.

C# Dll function declaration
	public static extern int getResults(TRecordField* Root);

C# struct implementation
unsafe public struct TRecordField
  public fixed byte Key[100];  // --> this one is filled correct with chars from a 
                               //     string
  public byte TypId;   // all other values remain 0
  public int Elemsize;
  public int Rows, Cols;
  public void* Buffer;

TRecordField Root;

C# function call
int Erg = NativeMethods.getResults(&Root);

What I have tried:

I tried some things like "[StructLayout(LayoutKind.Sequential)]" and "[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]", but it didnt work.
Tags: C#


When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the The Code Project Open License (CPOL).

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100