views:

143

answers:

4

Hi chaps(and chappettes)

Have a regular C dll with an exported function

int GetGroovyName(int grooovyId,char * pGroovyName, int bufSize,)

Basically you pass it an ID (int), a char * buffer with memory pre-allocated and the size of the buffer passed in.

pGroovyName gets filled with some text. (i.e. its a lookup basied on the groovyID)

The question is how do I best call that from c# ?

cheers

Buzz

+1  A: 

You may use DLLImport in C#.

Check this http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.aspx

Code from MSDN

using System;
using System.Runtime.InteropServices;

class Example
{
    // Use DllImport to import the Win32 MessageBox function.
    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);

    static void Main()
    {
        // Call the MessageBox function using platform invoke.
        MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
    }
}
jonaspp
-1 The example you posted does not allow the string to be modified by unmanaged code.
Gonzalo
+3  A: 

On the C# side, you would have:

[DllImport("MyLibrary")]
extern static int GetGroovyName(int grooovyId, StringBuilder pGroovyName, int bufSize);

And you call it like:

StringBuilder sb = new StringBuilder (256);
int result = GetGroovyName (id, sb, sb.Capacity); // sb.Capacity == 256
Gonzalo
+1 - using StringBuilder is better than using char[] like in my example.
Philip Wallace
A: 

Have a look at this snippet demonstrating (theoretically) how it should look:

using System;
using System.Runtime.InteropServices;
using System.Text; // For StringBuilder

class Example
{
    [DllImport("mylib.dll", CharSet = CharSet.Unicode)]
    public static extern int GetGroovyName(int grooovyId, ref StringBuilder sbGroovyName,  int bufSize,)

    static void Main()
    {
        StringBuilder sbGroovyNm = new StringBuilder(256);
        int nStatus = GetGroovyName(1, ref sbGroovyNm, 256);
        if (nStatus == 0) Console.WriteLine("Got the name for id of 1. {0}", sbGroovyNm.ToString().Trim());
        else Console.WriteLine("Fail!");
    }
}

I set the stringbuilder to be max capacity of 256, you can define something smaller, assuming it returns 0 is success, it prints out the string value for groovy id of 1, otherwise prints fail. Hope this helps. Tom

tommieb75
You beat me to it Gonzalo.... :)
tommieb75
Heh. Btw, no need for 'ref' there...
Gonzalo
Hi therewhen i step into the dll from that example the sbGroovyNm is a bad pointer and crashes the app...so the dll doesnt think there has been memory allocated to sbGroovyNmBuzz
Buzz
A: 

HURRAY! it WORKED

the key learning other than the cleverness supplied by everyone (and many thanks to everyone for your assistance) was the size of the LONGs in c++ vs the size of the LONGs in c#

hurry and thanks!

Buzz

Buzz