I am trying without success to write code in C# to pass a bitmap to an unmanaged c++ DLL and return a POINT structure.
I have done a lot of research on the internet, but have not found the "Gotcha" article or piece of code to help me resolve my issue.
The best I have been able to come up with so far is an unmanaged c++ DLL, wrapped with a managed c++ dll, called by my C# app. In testing that, I can pass simple types, such as an integer and return an integer with no problem. Now for the issue I am having, the bitmap.
I have tried passing an HBITMAP (using the GetHBitmap() function of my bitmap in c#), but I get errors during compile of "cannot convert parameter 1 from 'System::IntPtr' to 'HBITMAP'" and "Class1.FindImage(void *, void *) is inaccessible due to it's protection level".
Here is some of my code:
Main App:
class Program
{
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
this.X = x;
this.Y = y;
}
public static implicit operator System.Drawing.Point(POINT p)
{
return new System.Drawing.Point(p.X, p.Y);
}
public static implicit operator POINT(System.Drawing.Point p)
{
return new POINT(p.X, p.Y);
}
}
static void Main(string[] args)
{
Image src = Image.FromFile("Pin.png");
Image tgt = Image.FromFile("screen.png");
Bitmap bsrc = new Bitmap(src);
Bitmap btgt = new Bitmap(tgt);
IntPtr bs = bsrc.GetHbitmap();
IntPtr bt = btgt.GetHbitmap();
POINT p = Class1.FindImage(bs, bt);
}
}
ImportWrap.h:
namespace ImportWrap {
public ref class Class1
{
public:
static POINT FindImage(IntPtr source, IntPtr target);
};
}
ImportWrap.cpp:
static POINT FindImage(IntPtr source, IntPtr target)
{
return ImgFuncs::MyImgFuncs::FindImage(source, target);
}
ImgFuncs.h
typedef long LONG;
typedef void *PVOID;
typedef PVOID HANDLE;
typedef HANDLE HBITMAP;
typedef struct tagPOINT {
LONG x;
LONG y;
} POINT, *PPOINT;
namespace ImgFuncs
{
class MyImgFuncs
{
public:
static __declspec(dllexport) POINT FindImage(HBITMAP source, HBITMAP target);
};
}
ImgFuncs.cpp
namespace ImgFuncs
{
POINT MyImgFuncs::FindImage(HBITMAP source, HBITMAP target)
{
POINT p;
p.x = 1;
p.y = 2;
return p;
}
}
What am I doing wrong, or am I going completely off the map with my approach?
I would GLADLY entertain any suggestions regarding the correct way to code what I am trying to do.
I have some C++ code that is used to find an image within another image that works quite fast. Unfortunately, even using lockbits in c#, it's not fast enough. So I would like to make use of the c++ code for the image search.
I am sure I will run into further snags, but might be able to handle it if I can get past this stumbling block. As you can see, my C++ knowledge is limited.
You cannot use native struct types as a return value, C# can't handle them. Casting from IntPtr to HBITMAP requires a double cast. Like this:
static System::Drawing::Point FindImage(IntPtr source, IntPtr target)
{
POINT retval = ImgFuncs::MyImgFuncs::FindImage((HBITMAP)(void*)source, (HBITMAP)(void*)target);
return System::Drawing::Point(retval.X, retval.Y);
}
Add an assembly reference to System.Drawing. You might then also want to consider passing a Bitmap^ instead of an IntPtr to make it even easier to use.
You could probably skip the managed C++ wrapper entirely and just call the unmanaged DLL from C# via P/Invoke. Put something like this in your C# class
[DllImport("YourUnamangedDll.dll")]
private static extern POINT FindImage(IntPtr source, IntPtr target);
I haven't tested this, so you may need to tweak it as needed, but that's the general idea.
Related
I have an unmanaged DLL that exports only a C style factory method that returns a new instance of a class (simplified here to look simple).
hello.h
#if defined(HWLIBRARY_EXPORT) // inside DLL
# define HWAPI __declspec(dllexport)
#else // outside DLL
# define HWAPI __declspec(dllimport)
#endif
struct HelloWorld{
public:
virtual void sayHello() = 0;
virtual void release() = 0;
};
extern "C" HWAPI HelloWorld* GetHW();
hello.cpp
#include "hello.h"
struct HelloWorldImpl : HelloWorld
{
void sayHello(){
int triv;
std::cout<<"Hello World!";
std::cin>>triv;
};
void release(){
this->HelloWorldImpl::~HelloWorldImpl();
};
HelloWorld* GetHW(){
HelloWorld* ptr = new HelloWorldImpl();
return ptr;
};
Now, I can use dllimport to access GetHW() but is there a way to access the member functions of the returned 'struct'... ie, sayHello and release?
I was also stuck with the same problem. This question was asked a while before. I commented to it for any better solution but didn't get any reply yet. So, reposting it.
When i googled, able to find out two solutions.
Solution1: Expose all the member functions in the C-style for the existing dll. Which i cant do, as it is a 3rd party dll.
Solution2: Write a managed C++ dll exposing the functionality of native C++ dll, which later can be used in your C# dll. Here many classes/functions are present. So, creating would take most of the time.
i got the above solutions from the link below.
How To Marshall
Please let me know if there is any better solution other than the above two solutions?
i have the source code for C++ solution. But what i though was not to touch C++ dll. If there is any possibility to do it in C#, it would be great.
If there is no alternative, i need to follow any one of the specified two solutions.
The C++ code is using the way abstract classes are implemented by the Visual C++ compiler. http://blogs.msdn.com/b/oldnewthing/archive/2004/02/05/68017.aspx. This memory layout is "fixed" because it is used for implementing COM interfaces. The first member of the struct in memory will be a pointer to a vtable containing the function pointers of your methods. So for a
struct HelloWorldImpl : public HelloWorld
{
public:
int value1;
int value2;
}
the "real" layout in memory would be:
struct HelloWorldImpl
{
HelloWorldVtbl *vtbl;
int value1;
int value2;
}
where vtbl would be:
struct HelloWorldVtbl
{
void *sayHello;
void *release;
}
Just for the sake of doing a complete response, I'm writing the example for this signatures:
struct HelloWorld {
public:
virtual int sayHello(int v1, int v2, int v3) = 0;
virtual void release() = 0;
};
C# code:
[DllImport("NativeLibrary.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr GetHW();
[StructLayout(LayoutKind.Sequential)]
struct HelloWorldVtbl
{
public IntPtr sayHello;
public IntPtr release;
}
Your functions are void Func(void) or int Func(int, int, int), but in truth they have a hidden parameter, this, so you can write them as:
int sayHello(HelloWorld*, int, int, int);
void release(HelloWorld*);
so in C# the delegate is
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
public delegate int Int32MethodInt32Int32Int32(IntPtr ptr, int v1, int v2, int v3);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
public delegate void VoidMethodVoid(IntPtr ptr);
Then you can use
IntPtr ptr = GetHW();
IntPtr vtbl = Marshal.ReadIntPtr(ptr, 0);
HelloWorldVtblhw = (HelloWorldVtbl)Marshal.PtrToStructure(vtbl, typeof(HelloWorldVtbl));
Int32MethodInt32Int32Int32 sayHello = (Int32MethodInt32Int32Int32)Marshal.GetDelegateForFunctionPointer(hw.sayHello, typeof(Int32MethodInt32Int32Int32));
int res = sayHello(ptr, 1, 2, 3);
Console.WriteLine(res);
VoidMethodVoid release = (VoidMethodVoid)Marshal.GetDelegateForFunctionPointer(hw.release, typeof(VoidMethodVoid));
release(ptr);
I'm trying to wrap a C++ library (libclang) into a C# wrapper, using PInvoke.
Everything was shiny, until I tried to call a C++ method that returns a struct.
I did everything by the book, but when this method gets called, I get AccessViolationException.
Now, I read that it's probably because there's something messed up with the memory image of the objects. I checked and doublechecked if I've put all the arrtibutes and what nots everywhere but the Exception won't go away. (I've been looking at this code for hours, so I may have missed some things, you guys don't).
The C++ part (not my code, but I'm sure that it works):
CXString clang_formatDiagnostic(CXDiagnostic Diagnostic, unsigned Options) {
/* Parse the hell out of a lot of data, an then make a string
In the end, string gets wrapped in a custom struct: CXString.
*/
return createCXString(Out.str(), true);
}
Here's CXString:
typedef struct {
void *data;
unsigned private_flags;
} CXString;
So I have my C# classes to represent the wrapped C++ originals:
public class Diagnostic
{
private IntPtr _nativeObject;
internal IntPtr NativeObject { get { return _nativeObject; } }
[DllImport("libclang.dll", EntryPoint = "clang_formatDiagnostic")]
[return: MarshalAs(UnmanagedType.LPStruct)]
private static extern CXString FormatDiagnostic(IntPtr diag, uint options);
public Diagnostic(IntPtr native)
{
_nativeObject = native;
}
public string GetString(DiagnosticDisplayOptions options = DiagnosticDisplayOptions.DisplaySourceLocation)
{
var cxstr = FormatDiagnostic(_nativeObject, (uint)options); //<-- I get the exception here
return cxstr.GetString();
}
}
The functions I need are also implemented in a C taste (global) so, I can make an impression of OO in my C# classes, but in fact I store the IntPtr representations of the C++ objects (_nativeObject). So I'm pretty sure, that the object stored in the _nativeObject is in fact an CXDiagnostic (I got the reference returned from another function of the same library).
The actual object that I'm trying to use with FormatDiagnostic method gets initialized from the constructor of another wrapper class (TranslationUnit):
public TranslationUnit(/*lots of params to init the unit*/)
{
//... there are some int conversions and initialization failsafe codes here
//this is a property of TranslationUnit
Diagnostics = new List<Diagnostic>();
//GetDiagnosticsCount is also PInvoke to count CXDiagnostic objects related to the TranslationUnit
var dgCnt = (int)GetDiagnosticsCount(_nativeObject);
for (int i = 0; i < dgCnt; i++)
{
//GetDiagnostic is also PInvoke, gets the CXDiagnostic at the given index
var diag_ptr = GetDiagnostic(_nativeObject, (uint)i);
Diagnostics.Add(new Diagnostic(diag_ptr));
}
//up until now, all the calls seem to work
//I get the expected count of diagnostics and none of the other
//PInvoke calls throw exceptions. They use IntPtrs, but none of them
//use structs.
}
So as the MSDN tutorial suggested, I've made a C# class to Marshal the CXString struct into, and it looks like this:
[StructLayout(LayoutKind.Sequential)]
public class CXString
{
public IntPtr data;
public uint private_flags;
}
I get the AccessViolationException when the code reaches FormatDiagnostic call.
Any tips where it could have gone wrong?
EDIT:
CXDiagnostic is a pointer type in the original C++ code:
typedef void *CXDiagnostic;
I think marshalling to LPStruct is not proper here and the CXString class needs to be struct.
Try the following code:
public class Diagnostic
{
...
[DllImport("libclang.dll", EntryPoint = "clang_formatDiagnostic")]
private static extern CXString FormatDiagnostic(IntPtr diag, uint options);
...
}
[StructLayout(LayoutKind.Sequential)]
public struct CXString
{
public IntPtr data;
public uint private_flags;
}
Also, you should take care of the calling convention (StdCall by default, but for example pure C use Cdecl) and the struct byte alignment.
I've worked on a C# version of a C++ API but I can't manage to get it right.
Since the whole API was too big the first time I posted, I've cut it down to some core functions for which I really need some help to make a managed version of.
So basically, this is a C++ dll containing exported functions that are used to communicate with a technical analysis software.
C++ function I'd like to convert
#define PLUGINAPI extern "C" __declspec(dllexport)
PLUGINAPI int GetFunctionTable( FunctionTag **ppFunctionTable )
{
*ppFunctionTable = gFunctionTable;
// must return the number of functions in the table
return gFunctionTableSize;
}
GetFunctionTable is called by the software which provides a pointer to an array of FunctionTag called gFunctionTable:
typedef struct FunctionTag
{
char *Name;
FunDesc Descript;
} FunctionTag;
FunctionTag gFunctionTable[] = {"ExampleA",{ VExampleA, 0, 0, 0, 0, NULL },
"ExampleB",{ VExampleB, 1, 0, 1, 0, NULL }
};
FunctionTag structure contains an embedded structure called Fundesc:
// FunDesc structure holds the pointer to actual
// user-defined function that can be called by AmiBroker.
typedef struct FunDesc
{
AmiVar (*Function)( int NumArgs, AmiVar *ArgsTable );
UBYTE ArrayQty; // number of Array arguments required
UBYTE StringQty; // number of String arguments required
SBYTE FloatQty; // number of float args
UBYTE DefaultQty; // number of default float args
float *DefaultValues; // the pointer to defaults table
} FunDesc;
Finally, Fundesc contains AmiVar type:
#pragma pack( push, 2 )
typedef struct AmiVar
{
int type;
union
{
float val;
float *array;
char *string;
void *disp;
};
} AmiVar;
#pragma pack(pop)
C# conversion so far
Now, this is what I've written so far in an attempt to get my C# dll to "mimic" the C++ original API. The GetFunctionTable() exported function:
namespace AmiBrokerFrontDll
{
internal static class AmiBrokerFrontDll
{
[DllExport("GetFunctionTable", CallingConvention = CallingConvention.Cdecl)]
public static Int32 GetFunctionTable(ref FunctionTag[] ppFunctionTable)
{
FillFunction();
ppFunctionTable=gFunctionTable;
return gFunctionTableSize;
}
Then comes the definition of FunctionTag structure and gFunctionTableSize:
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct FunctionTag
{
[MarshalAs(UnmanagedType.LPStr)]
public string Name;
public FunDesc Description;
}
public static FunctionTag[] gFunctionTable=new FunctionTag[1];
public static FunctionTag gfunc;
static Int32 gFunctionTableSize = Marshal.SizeOf(gFunctionTable) / Marshal.SizeOf(gfunc);
public static void FillFunction()
{
gFunctionTable[0].Name = "VExempleA";
gFunctionTable[0].Description.Function += VExempleDeMacd;
//ArrayQty, StringQty, FloatQty, DefaultQty, DefaultTablePtr
gFunctionTable[0].Description.ArrayQty = 0;
gFunctionTable[0].Description.StringQty = 0;
gFunctionTable[0].Description.FloatQty = 2;
gFunctionTable[0].Description.DefaultQty = 0;
gFunctionTable[0].Description.DefaultValues = new IntPtr();
}
FunDesc declaration includes a delegate:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate AmiVar FunctionDelegate(int NumArgs, ref AmiVar ArgsTable);
public struct FunDesc
{
[MarshalAs(UnmanagedType.FunctionPtr)]
public FunctionDelegate Function;
public byte ArrayQty; // The number of Array arguments required
public byte StringQty; // The number of String arguments required
public byte FloatQty; // The number of float args
public byte DefaultQty; // The number of default float args
public IntPtr DefaultValues; // The pointer to defaults table
}
Finally, we have an AmiVar structure:
[StructLayoutAttribute(LayoutKind.Explicit, Size = 8)]
public struct AmiVar
{
[FieldOffset(0)]
public Int32 type;
[FieldOffset(4)]
public Single val;
[FieldOffset(4)]
public IntPtr array;
[FieldOffset(4)]
[MarshalAs(UnmanagedType.LPStr)]
public string name;
[FieldOffset(4)]
public IntPtr disp;
}
Sorry this is too long. Unfortunately, I couldn't make a small consise question.
So this code compiled (maybe not anymore since this is an extract from the bigger picture) but when loading the resulting dll from the technical analysis software, I received an ACCESS VIOLATION ERROR. I believe this means the C# conversion doesn't map the C++ variables size correctly. With the arrays of structures and delegates this project has become too difficult for me to solve alone.
Any help will be much appreciated!
Thanks,
Guillaume
I can't help in your specific case, but I can tell you a couple things that will make your life easier:
Function pointers created from managed delegates should never, ever, ever, be stored in unmanaged code. I don't say this lightly. There are claims that if you create a function pointer from a delegate with GetFunctionPointerForDelegate, that the appropriate thunks will get created and won't ever get garbage collected. This is NOT true. I have watched function pointers that were good on one call go sour on the next. The safest bet is to guarantee that function pointers will never get stored beyond the use of an unmanaged call.
P/Invoke is OK for some tasks, but by far the easiest way to integrate a non-C#-friendly C++ library is to make a better/more appropriate wrapper for it in C++/CLI. See here for a description of one way to approach the problem.
Is it possible to call a c(++) static function pointer (not a delegate) like this
typedef int (*MyCppFunc)(void* SomeObject);
from c#?
void CallFromCSharp(MyCppFunc funcptr, IntPtr param)
{
funcptr(param);
}
I need to be able to callback from c# into some old c++ classes. C++ is managed, but the classes are not ref classes (yet).
So far I got no idea how to call a c++ function pointer from c#, is it possible?
dtb is right. Here a more detailed example for Marshal.GetDelegateForFunctionPointer. It should work for you.
In C++:
static int __stdcall SomeFunction(void* someObject, void* someParam)
{
CSomeClass* o = (CSomeClass*)someObject;
return o->MemberFunction(someParam);
}
int main()
{
CSomeClass o;
void* p = 0;
CSharp::Function(System::IntPtr(SomeFunction), System::IntPtr(&o), System::IntPtr(p));
}
In C#:
public class CSharp
{
delegate int CFuncDelegate(IntPtr Obj, IntPtr Arg);
public static void Function(IntPtr CFunc, IntPtr Obj, IntPtr Arg)
{
CFuncDelegate func = (CFuncDelegate)Marshal.GetDelegateForFunctionPointer(CFunc, typeof(CFuncDelegate));
int rc = func(Obj, Arg);
}
}
Have a look at the Marshal.GetDelegateForFunctionPointer method.
delegate void MyCppFunc(IntPtr someObject);
MyCppFunc csharpfuncptr =
(MyCppFunc)Marshal.GetDelegateForFunctionPointer(funcptr, typeof(MyCppFunc));
csharpfuncptr(param);
I don't know if this really works with your C++ method, though, as the MSDN documentation states:
You cannot use this method with function pointers obtained through C++
I want to use PInvoke to bring to managed side something this:
(C code)
typedef struct{
//some fields...
} A;
type struct{
A* a;
} B;
int getB(B* destination){ //destionation will be an output parameter to C#
//puts an B in 'destination'
return 0;
}
Now, I need a way to tell managed side how to marshalling B from C to C# structure or class. I've tryed many things such as IntPtr fields, MarchalAs atributes, but with no success. I will not expose here the code that I've tryed to keep the question simple. However i could do it as long answers arrive.
If it were me, I would just use unsafe code and use pointers on the C# side:
public unsafe class UnmanagedStuff {
public struct A {
// some fields
}
public struct B {
public A* a;
}
// Add appropriate PInvoke attribute here
public static extern int getB(B* destination);
public static void UseBForSomething() {
B b;
getB(&b);
// Do something with b
}
}
You can do that using the Marshal class.
// Define a C# struct to match the unmanaged one
struct B
{
IntPtr a;
}
[DllImport("dllName")]
extern int getB(IntPtr destination);
B GetB()
{
IntPtr ptrToB = IntPtr.Zero;
getB(ptrToB);
return (B)Marshal.PtrToStructure(ptrToB, typeof(B));
}