I have a problem, I'm doing some C#<->C++ interop via a C interface and I have a function that I import from a dll like this
[DllImport("pixi_api", EntryPoint = "pixi_sprite_asm_file", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(PixiStringMarshaler))]
private static extern pixi_string _pixi_sprite_asm_file(IntPtr sprite);
and it gets called, for example, like this
var cstr = _pixi_sprite_asm_file(data_pointer);
the actual function in the DLL looks like this
EXPORT pixi_string pixi_sprite_asm_file(pixi_sprite_t pixi_sprite_ptr) {
const char* const ptr = pixi_sprite_ptr->asm_file;
pixi_string str = {ptr, static_cast<int>(strlen(ptr))};
return str;
}
however there's a problem:
if I print the data_pointer passed from the C# code, before the call to _pixi_sprite_asm_file and then I print it while inside the c native function call (the pixi_sprite_ptr), I get 2 completely different pointers and as such, everything explodes.
e.g:
data_pointer => 191BF4A0300
pixi_sprite_ptr => 0x00007ffc0e1ebb92
I have other methods that return simple-to-marshal types such as ints, that don't have this problem and the pointer gets passed unchanged.
e.g this one works, the pointers are the same and it returns the expected value:
[DllImport("pixi_api", EntryPoint = "pixi_sprite_line", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I4)]
private static extern int _pixi_sprite_line(IntPtr sprite);
I have no clue what could be going wrong.
An example of what it looks like when called
I am attempting to access a Newlands scanner using Platform Invoke from a c# program.
It should be relatively straight forward.
I set up my P/Invoke and and call it.
[DllImport("NLcpfw.dll", EntryPoint = "cpfw_open", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr cpfw_open(string pwStrPort,
string pwStrParam,
int nMode);
public static void CallFromHere(){
IntPtr hDev = cpfw_open("udp", "", CPFW_OM_NORMAL);
//GCHandle handle = GCHandle.Alloc(HNLCPFW, GCHandleType.Pinned);
System.Diagnostics.Debug.Assert(hDev != null);
NewlandInterface.cpfw_close(hDev);
}
Some how it is not picking it up.
I get a BadImageFormatException was unhandled
Make sure it is a valid managed assembly
Make sure you have supplied a correct path for the assembly
The C++ header reads
__declspec(dllimport) HNLCPFW WINAPI cpfw_open(WCHAR *pwStrPort, WCHAR *pwStrParam, int nMode = CPFW_OM_NORMAL);
typedef struct
{
void* hDev;
int nMode;
PNLCPFW_PLUG_API DevAPI;
HINSTANCE hPlugDll;
void *exData;
}NLCPFW,*HNLCPFW;
I'm assuming it is ok just to take a IntPtr in my p\Invoke code.
Any ideas as to why this is happening would be much appreciated.
I have copied all of the dll's in with the exe. In this case these are
NLcpfw.dll, cpfw_udp.dll, cpfw_tcp.dll,cpfw_hidpos.dll etc
Thanks leppie I need to change the platform to X86
Is there an analogue of the function GetColorDirectory?
Or should I just call through a DLL?
The purpose is to get the path to the system directory with color profiles
As per MSDN you call it using the API:
[DllImport(DllImport.Mscms, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern bool GetColorDirectory(IntPtr pMachineName, StringBuilder pBuffer, ref uint pdwSize);
I have the following function in C++ native dll, and I want to use it in a C# app.
DWORD __cdecl Foo(
LPCTSTR Input,
TCHAR** Output,
DWORD Options,
ErroneousWord** List = NULL,
LPDWORD Count = 0
);
Using Pinvoke
[DllImport("dllName", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern UInt32 Foo(string InputWord, out string Output, UInt32 Options, out object List,out UInt32 Count);
Calling code:
string output;
object dummyError = null;
uint dummyCount = 0;
uint x = 0;
Foo(Text, out output, x | y,out dummyError,out dummyCount);
I got the following exception
Attempted to read or write protected
memory. This is often an indication
that other memory is corrupt
P.S:
ErroneousWord is struct and I do not need its output, so I marshal it as object
That error more than likely means that you have a marshaling problem.
You don't show us what the ErroneousWord type is, but I assume it's some kind of class defined in your C++ code. My guess is that it's not being marshaled correctly to a .NET object.
Considering that it's a pointer (or a pointer to a pointer), try changing that parameter to an IntPtr type to represent a pointer, instead. It shouldn't matter, since you're simply passing NULL for the argument anyway, easily represented using the static IntPtr.Zero field.
You probably also want to marshal Output the exact same way. If you change the parameter to an IntPtr type, you'll receive a pointer to a TCHAR*, which you can then pass to the other unmanaged functions however you see fit (e.g., to free it).
Try the following code:
[
DllImport("dllName",
CharSet = CharSet.Unicode,
CallingConvention = CallingConvention.Cdecl)
]
public static extern UInt32 Foo(
string InputWord,
out IntPtr Output, // change to IntPtr
UInt32 Options,
out IntPtr List, // change to IntPtr
out UInt32 Count);
IntPtr output;
IntPtr dummyError = IntPtr.Zero;
uint dummyCount = 0;
uint x = 0;
Foo(Text, out output, x | y, out dummyError, out dummyCount);
You might also need to use the Marshal.AllocHGlobal method to allocate unmanaged memory from your process that is accessible to the C++ code. Make sure that if you do so, you also call the corresponding Marshal.FreeHGlobal method to release the memory.
Given Cody's answer and the comments, you will have to do it this way:
[DllImport("dllName", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
extern static UInt32 Foo(string InputWord, out IntPtr Output, UInt32 Options, out IntPtr List, out UInt32 Count);
Now to get the string value in Output marshalled over to managed memory you will do:
string outputValue = Marshal.PtrToStringAnsi(Output);
You must know if TCHAR is Ansi or Unicode and use the appropriate marshal.
Remember to hang onto the Output IntPtr so you can pass that to the native Free method.
Thanks Cody for your answer but I want to make a seperate one, first Output is created by Foo from the native side, and I call FreeFoo to free the allocated memory by Foo.
The following is the code
[DllImport("dllname", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern UInt32 Correct(string InputWord, out IntPtr Output, UInt32 Options, out object List,out UInt32 Count);
[DllImport("dllname", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern void FreeFoo(IntPtr Output);
}
To use it:
public string FooWrapper(string Text)
{
IntPtr output;
object dummyError = null;
uint dummyCount = 0;
uint x = 0;
Foo(Text, out output, x,out dummyError,out dummyCount);
string str = Marshal.PtrToStringUni(output);
FreeFoo(output);
return str;
}
Whatever the ErroneousWord type is, you can't marshal an array as a single out object. If it is at all possible to marshal as an object...
I try to use a VB6 DLL in a C# Program. But I allways get a AccessViolationException. Maybe you can tell me what Im doing wrong.
I created a Test-VB6-DLL like in this tutorial:
http://oreilly.com/pub/a/windows/2005/04/26/create_dll.html
Then I tried to use this DLL dynamically like in this Post:
http://blogs.msdn.com/b/jonathanswift/archive/2006/10/03/dynamically-calling-an-unmanaged-dll-from-.net-_2800_c_23002900_.aspx?PageIndex=3#comments
But also if I try it by using [DLLImport]. I allways run into the AccessViolationException.
Maybe someone can give me a hint.
regards
viktor
P.S.: What I was able to do is to create a reference to an existing DLL. But this approach has the disadvantage, that I have to update all the references if the DLL is updated. And this will happen (more or less) open because to dlls are part of a softwareproject that is under developmen. Maybe there is a possibility to update the references without to need to recompile the C# program?
#MarkJ: No - binary compatibility brought no success.
Here are the sources:
The VB6-Dll:
Option Explicit
Public Function Increment(var As Integer) As Integer
If Not IsNumeric(var) Then Err.Raise 5
Increment = var + 1
End Function
And here the C# code that tries to use the VB6 Dll:
class Program
{
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr LoadLibrary(String DllName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, byte[] procedureName);
static void Main(string[] args)
{
IntPtr pDll = LoadLibrary(#"P:\dev\Path\to\TestProjekt.dll");
string x = "Increment";
Encoding e = Encoding.GetEncoding("ISO-8859-1");
byte[] b = e.GetBytes(x);
IntPtr pAddressOfFunctionToCall = GetProcAddress(pDll, b);
Increment inc = Increment)Marshal.
GetDelegateForFunctionPointer(pAddressOfFunctionToCall,
typeof(Increment));
int a = inc(5); // <---- Here the AccessViolationException is thrown
return;
}
}
In the meantime I have read any doc I could find but still I don't habe any idea why this ist not working grgrgrgrgr
regards
viktor
Your byte[] b has no terminating null, so isn't a valid unmanaged LPCSTR. I don't understand why you are fiddling about trying to encode the method name by hand, instead of declaring GetProcAddress like this and having the Framework interop code take care of the marshalling for you:
public static extern IntPtr GetProcAddress(IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)] string procedureName);
You must check the return value (pAddressOfFunctionToCall). When it isIntPtr.Zero as I believe you are getting, because your lpProcName argument to GetProcAddress is wrong, then attempting to call through its Delegate wrapper will always give an AccessViolationException.
Also, don't omit to call FreeLibrary on the module handle when you are done.