Reputation: 67
I have to access dynamic library using C#. It works great when using COM library however when I try to use Dynamic library, it causing error.
1st problem
At first i do my code like this:
[DllImport("mydll.dll")]
public static extern int toGetInfo(uint id, char[] strVolume, char[] strInfo);
// strVolume and strInfo is parameter that return value with [out]
public static void Main()
{
char[] test1,test2;
toGetInfo(0,test1,test2);
}
But it unable to compile with error use of unassigned local variable for test1 and test2 . Then I edit my code by adding out like this:
[DllImport("mydll.dll")]
public static extern int toGetInfo(uint id, out char[] strVolume, out char[] strInfo);
// strVolume and strInfo is parameter that return [out]
public static void Main()
{
char[] test1,test2;
toGetInfo(0, out test1, out test2);
}
It able to compile but returns null value to test1 and test2.
2nd problem
[DllImport("mydll.dll")]
public static extern int toOpen(uint id, char* name);
public static void Main()
{
char name;
toOpen(0, name);
}
When compile it give error "Pointers and fixed size buffers may only be used in an unsafe context"
Any idea how to do it?
Upvotes: 0
Views: 485
Reputation: 34421
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication74
{
class Program
{
[DllImport("mydll.dll")]
public static extern int toGetInfo(uint id, IntPtr strVolume, IntPtr strInfo);
[DllImport("mydll.dll")]
public static extern int toOpen(uint id, IntPtr name);
const int STRING_LENGTH = 256;
static void Main(string[] args)
{
IntPtr strVolumePtr = Marshal.AllocHGlobal(STRING_LENGTH);
IntPtr strInfoPtr = Marshal.AllocHGlobal(STRING_LENGTH);
uint id = 123;
int status1 = toGetInfo(id, strVolumePtr, strInfoPtr);
string strVolume = Marshal.PtrToStringAnsi(strVolumePtr);
string strInfo = Marshal.PtrToStringAnsi(strInfoPtr);
string name = "John";
IntPtr openNamePtr = Marshal.StringToHGlobalAnsi(name);
int status2 = toOpen(id, openNamePtr);
Marshal.FreeHGlobal(strVolumePtr);
Marshal.FreeHGlobal(strInfoPtr);
Marshal.FreeHGlobal(openNamePtr);
}
}
}
Upvotes: 1