I created a C# application which use 2 C++ Dll, the first one work very well, but i have some trouble with the second.
I'm flashing a CPU :
My dll :
[DllImport(#"st10flasher.dll")]
public static extern long SetCom(string PortName, long comspeed);
[DllImport(#"st10flasher.dll")]
public static extern long LoadFile(string FileName, ref long Fsize);
[DllImport(#"st10flasher.dll")]
public static extern long InitMonitor(string device);
[DllImport(#"st10flasher.dll")]
public static extern long ProgramFlash();
[DllImport(#"st10flasher.dll")]
public static extern long EraseFlash(long Block);
[DllImport(#"st10flasher.dll")]
public static extern long CloseCom();
[DllImport(#"st10flasher.dll")]
public static extern long BlockNBToErase(bool EraseBlockError);
It usually work but sometime it crash with.
-I checked the event log and found the exception code : 0xc0000409
-It ask me if i want to debug it with VS then i have this stack :
The Error message isn't in english i'll try to translate :
unmanaged exception 0x71E2CF1B (clr.dll). the instrumentation code stack cookie detected exceeding the stack buffer
What could it be ? thanks !
As you asked i added the VB declaration :
Declare Function SetCom Lib "st10flasher.dll" (ByVal PortName$, ByVal comspeed As Long) As Long
Declare Function LoadFile Lib "st10flasher.dll" (ByVal FileName$, ByRef Fsize As Long) As Long
Declare Function InitMonitor Lib "st10flasher.dll" (ByVal device As Any) As Long
Declare Function ProgramFlash Lib "st10flasher.dll" () As Long
Declare Function GetError Lib "st10flasher.dll" (ByVal BufferForStatus As Any) As Long
Declare Function EraseFlash Lib "st10flasher.dll" (ByVal Block As Long) As Long
Declare Function CloseCom Lib "st10flasher.dll" () As Long
/************************************************** EDIT **************************************************/
So i updated my functions declaration like that :
[DllImport(#"st10flasher.dll")]
public static extern uint SetCom([MarshalAs(UnmanagedType.LPStr)] string PortName, uint comspeed);
[DllImport(#"st10flasher.dll")]
public static extern uint LoadFile([MarshalAs(UnmanagedType.LPStr)] string FileName, ref uint Fsize);
[DllImport(#"st10flasher.dll")]
public static extern uint InitMonitor([MarshalAs(UnmanagedType.LPStr)] string device);
[DllImport(#"st10flasher.dll")]
public static extern uint ProgramFlash();
[DllImport(#"st10flasher.dll")]
public static extern uint EraseFlash(uint Block);
[DllImport(#"st10flasher.dll")]
public static extern uint CloseCom();
[DllImport(#"st10flasher.dll")]
public static extern uint BlockNBToErase(bool EraseBlockError);
and i found the dll's documentation :
unsigned int SetCom(char *PortName, unsigned int ComSpeed)
unsigned int CloseCom(void)
unsigned int LoadFile(char *filename)
unsigned int InitMonitor(char *target)
unsigned int EraseFlash(unsigned int BlockMask)
unsigned int ProgramFlash(void)
i tried to update my prototype using this post : post StackOverflow But i still have the same error. Did i misunderstood something from the link ?
/******************************SOLVED****************************/
I solved my problem by creating an other C++ DLL which load and unload the st10flasher.dll
[DllImport(#"st10flasher.dll")]
public static extern uint LoadFile([MarshalAs(UnmanagedType.LPStr)] string FileName, ref uint Fsize);
seems wrong:
unsigned int LoadFile(char *filename)
remove the ref uint Fsize
You didn't have a signature for this:
[DllImport(#"st10flasher.dll")]
public static extern uint BlockNBToErase(bool EraseBlockError);
Everything else should be correct.
Related
In C++, calling this function is just as simple as:
CertEnumSystemStore(CERT_SYSTEM_STORE_CURRENT_USER, NULL, NULL, (PFN_CERT_ENUM_SYSTEM_STORE)addr);
Addr would just be the base address of where the function resides
In C#, you can't just pass in an address, and will have to pass in a function, which is not what I want in this case. Below is a snippet of my code
public delegate bool CertEnumSystemStoreCallback([In, MarshalAs(UnmanagedType.LPWStr)] String pvSystemStore, uint dwFlags, ref CERT_SYSTEM_STORE_INFO pStoreInfo, uint pvReserved, [In, MarshalAs(UnmanagedType.LPWStr)] String pvArg);
[DllImport("crypt32.dll", CharSet = CharSet.Unicode)]
public static extern uint CertEnumSystemStore(uint dwFlags, uint pvSystemStoreLocationPara, String pvArg, CertEnumSystemStoreCallback pfnEnum);
[StructLayout(LayoutKind.Sequential)]
public struct CERT_SYSTEM_STORE_INFO
{
uint cbSize;
}
CertEnumSystemStore(CERT_SYSTEM_STORE_CURRENT_USER, 0, null, (CertEnumSystemStoreCallback)addr);
I get a type conversion error that tells me it can't cast type InPtr to type CertEnumSystemStoreCallback.
What can I do to just pass an address containing the function instead of having to supply the function name itself?
I'm trying to build a struct for LDAP in C#, but I if I try to convert the InPtr to the struct I defined it throws the following exception:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
[DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_sslinitW",
SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr ldap_sslinit(string hostName, uint portNumber, int secure);
//https://learn.microsoft.com/en-us/windows/win32/api/winldap/ns-winldap-ldap
[StructLayout(LayoutKind.Sequential)]
public struct LDAP
{
[StructLayout(LayoutKind.Sequential)]
struct ld_sb
{
System.UIntPtr sb_sd;
byte Reserved1;
System.UIntPtr sb_naddr;
byte Reserved2;
}
string ld_host;
UInt32 ld_version;
byte ld_lberoptions;
UInt32 ld_deref;
UInt32 ld_timelimit;
UInt32 ld_sizelimit;
UInt32 ld_errno;
string ld_matched;
string ld_error;
ulong ld_msgid;
string Reserved3;
UInt32 ld_cldaptries;
UInt32 ld_cldaptimeout;
UInt32 ld_refhoplimit;
UInt32 ld_options;
}
private const uint LDAP_SSL_PORT = 636;
static void Main(string[] args)
{
IntPtr ld = ldap_sslinit("test", LDAP_SSL_PORT, 1);
var ldap = Marshal.PtrToStructure(ld, typeof(LDAP));
}
Before this I tried to declare the ldapsslinit method with private static extern LDAP ldap_sslinit(string hostName, uint portNumber, int secure); However, it returns the following error:
'Method's type signature is not PInvoke compatible.'
I think the problem is caused by the LDAP struct I defined, but I don't known which type from unmanged to managed was wrong.
unmanaged
managed
UINT_PTR
UIntPtr
UCHAR*
byte[]
ULONG_PTR
UIntPtr
PCHAR
string
ULONG
UInt32
UCHAR
byte
Did I use the wrong mapping in this table?
What specifically are you trying to accomplish. There are managed types in C# for connecting to and using LDAP that don't require native implementations like you are trying to use.
If for some reason you need the native implementation (Note: since you are stuck on step one of a complex handshake I would recommend using a managed implemtation), Instead of the c++ definition of the nested ldap_sslinit struct declare it outside of LDAP
struct ld_sb
{
System.UIntPtr sb_sd;
byte Reserved1;
System.UIntPtr sb_naddr;
byte Reserved2;
}
public struct LDAP
{
ld_sb ld_sb;
string ld_host;
//...
}```
First: I'm sorry if the title is wrong. I'm not sure how to name my problem.
In my C API I have a function:
MYAPI_STATUS SetParam(void *hInst, unsigned long param, void *value);
This function accepts different types of pointers depending on param type. Like this:
SetParam(hInst, 1, (void*)"somevalue");
int x = 55;
SetParam(hInst, 2, &x);
I'm just writing a wrapper/binding in C# and I have a problem.
[DllImport("myapi", CallingConvention = CallingConvention.Cdecl]
public static extern uint SetParam(IntPtr hInst, uint paramCode, IntPtr paramValue);
What's the best way to replicate behaviour from C? So the function would look like:
public static uint SetParam(IntPtr hInst, uint paramCode, ref object paramValue);
or possibly:
public static uint SetParam(IntPtr hInst, uint paramCode, object paramValue);
I solved it by marshalling manually first checking type of object if the object is string then I use Marshal.StringToHGlobalAnsi if it's something else then I marshall differently based on what I need.
If someone has any better solution feel free to write :)
The * sign in C programming means give parameter by reference, so this code is not match:
public static uint SetParam(IntPtr hInst, uint paramCode, object paramValue);
Because it gives parameter by value.
This code is very similar to what you want:
public static uint SetParam(IntPtr hInst, uint paramCode, ref object paramValue);
But there is a bit difference. When you using ref before a parameter you have to initialize it before sending to the method, but by using out you don't have this limitation for passing it. So I think the best possible match will be this code:
public static uint SetParam(IntPtr hInst, uint paramCode, out object paramValue);
I am working with SQL VDI and attempting to pass a structure from C# to C++ via a COM interface. The structure is defined in the C++ header as:
#pragma pack(8)
struct VDConfig
{
unsigned long deviceCount;
unsigned long features;
unsigned long prefixZoneSize;
unsigned long alignment;
unsigned long softFileMarkBlockSize;
unsigned long EOMWarningSize;
unsigned long serverTimeOut;
unsigned long blockSize;
unsigned long maxIODepth;
unsigned long maxTransferSize;
unsigned long bufferAreaSize;
} ;
To emulate this, I have defined the structure in C# as:
[StructLayout(LayoutKind.Explicit)]
public struct VDConfig
{
[FieldOffset(0)]
public uint deviceCount;
[FieldOffset(4)]
public uint features;
[FieldOffset(8)]
public uint prefixZoneSize;
[FieldOffset(12)]
public uint alignment;
[FieldOffset(16)]
public uint softFileMarkBlockSize;
[FieldOffset(20)]
public uint EOMWarningSize;
[FieldOffset(24)]
public uint serverTimeout;
[FieldOffset(28)]
public uint blockSize;
[FieldOffset(32)]
public uint maxIODepth;
[FieldOffset(36)]
public uint maxTransferSize;
[FieldOffset(40)]
public uint bufferAreaSize;
}
I have also tried to define the structure as LayoutKind.Sequential and tried it with Pack=8. However I define the structure, when I attempt to pass it to the function, it fails and I receive the error "Alignment must be 2**n and <= system allocation granularity." I've tried defining the function that accepts the structure as:
int CreateEx([MarshalAs(UnmanagedType.LPWStr)]string instanceName,
[MarshalAs(UnmanagedType.LPWStr)]string name,
IntPtr config);
and
int CreateEx([MarshalAs(UnmanagedType.LPWStr)]string instanceName,
[MarshalAs(UnmanagedType.LPWStr)]string name,
ref VDConfig config);
I get the same result with either definition. Can anyone tell me what I'm doing wrong here?
Edit:
In looking a little closer, I'm also getting the error "Device count must be in [1..64]." I'm setting the device count to 1 and in concert with the error above, it almost looks like the function isn't getting my structure at all. Don't know if this helps or not, but maybe it'll spark something for someone.
Per request, here are the interface structures. In C++:
MIDL_INTERFACE("d0e6eb07-7a62-11d2-8573-00c04fc21759")
IClientVirtualDeviceSet2 : public IClientVirtualDeviceSet
{
public:
virtual HRESULT STDMETHODCALLTYPE CreateEx(
/* [in] */ LPCWSTR lpInstanceName,
/* [in] */ LPCWSTR lpName,
/* [in] */ struct VDConfig *pCfg) = 0;
virtual HRESULT STDMETHODCALLTYPE OpenInSecondaryEx(
/* [in] */ LPCWSTR lpInstanceName,
/* [in] */ LPCWSTR lpSetName) = 0;
};
And my C# version:
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("d0e6eb07-7a62-11d2-8573-00c04fc21759")]
public interface IClientVirtualDeviceSet2
{
void CreateEx([In, MarshalAs(UnmanagedType.LPWStr)]string instanceName,
[In, MarshalAs(UnmanagedType.LPWStr)]string name,
[In]ref VDConfig config);
void OpenInSecondaryEx([MarshalAs(UnmanagedType.LPWStr)]string instanceName,
[MarshalAs(UnmanagedType.LPWStr)]string lpSetName);
}
For anyone else who comes across this, this is the answer:
As you can see in vdi.h, IClientVirtualDeviceSet2 "inherits" from IClientVirtualDeviceSet. As far as COM is concerned, there is no such thing as interface inheritance.
Therefore, when calling CreateEx on IClientVirtualDeviceSet2, you're actually calling Create on IClientVirtualDeviceSet (because Create is the first method in the vtable of that combined IClientVirtualDeviceSet + IClientVirtualDeviceSet2). That's why you end up getting invalid parameters.
The fix for this is to create a single interface (IClientVirtualDeviceSet2) with all the methods, IClientVirtualDeviceSet first, then the two IClientVirtualDeviceSet2 methods (obviously in order). This ensures when CreateEx() is called, it uses the correct DispId.
I'm sure you could probably use inheritance and set the DispIdAttribute accordingly:
https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dispidattribute(v=vs.110).aspx
but there is probably little point.
I have a dll which accepts a struct that contains a pointer to a function to do a callback.
How can I get an IntPtr to a function of my application to build the struct?
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class OPERATION {
public uint OperationID;
public IntPtr Context;
public IntPtr Callback; -> How to pass this?
}
Here is the delegate accepting the OPERATION struct
public delegate void MY_CALLBACK([In] OPERATION operation, [In] uint msgId, [In] IntPtr msgDataPtr);
use Marshal.GetFunctionPointerForDelegate
Maybe the Marshal.GetFunctionPointerForDelegate method may help you.