Buzz
Buzz

Reputation: 11

calling function from regular dll from c# - memory allocation issue?

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

Upvotes: 0

Views: 745

Answers (3)

t0mm13b
t0mm13b

Reputation: 34592

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

Upvotes: 0

Gonzalo
Gonzalo

Reputation: 21175

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

Upvotes: 3

jonaspp
jonaspp

Reputation: 134

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);
    }
}

Upvotes: 1

Related Questions