Using GhostScript 9.10 in Windows with Unicode characters in parameters - c#

I want to use Ghostscript in a .NET / C# application to convert a .tiff file to PDF.
My problem: When the file path contains non-ansi characters (e.g. Umlaute), the function
gsapi_init_with_args
fails. (With GS 8.x, it works fine!).
I found information that the behaviour was changed in 9.x, and I also found a function called
gsapi_init_with_argsW
And this function should work with .NET without any problems (see http://permalink.gmane.org/gmane.comp.printing.ghostscript.cvs/31721)
So I use the following DLLImport:
[DllImport(#"gsdll32.dll")]
public static extern int gsapi_init_with_argsW( IntPtr instace, int argc, string[] argv);
but this still does not work, I get the error:
Error: /undefinedfilename
in (C:\\304NDERUNGEN\\TEST.PDF)
The name of the file schould be
C:\\ÄNDERUNGEN\\TEST.PDF
so the umlaut "Ä" is not recognized correctly.
I´ve search the web a lot but did not found a solution.
Any idea?
Thank you!

I suspect that you will need to use UTF-8 here. Make a call to gs_set_arg_encoding passing GS_ARG_ENCODING_UTF8.
Any strings that you pass to Ghostscript should be declared as IntPtr. To convert from a C# string to a null-terminated UTF-8 encoded string use this function provided by Hans Passant:
public static IntPtr NativeUtf8FromString(string managedString)
{
int len = Encoding.UTF8.GetByteCount(managedString);
byte[] buffer = new byte[len + 1]; // null-terminator allocated
Encoding.UTF8.GetBytes(managedString, 0, managedString.Length, buffer, 0);
IntPtr nativeUtf8 = Marshal.AllocHGlobal(buffer.Length);
Marshal.Copy(buffer, 0, nativeUtf8, buffer.Length);
return nativeUtf8;
}
Make sure that you remember to clean up with a call to Marshal.FreeHGlobal.
The overall code might look a little like this:
public class Ghostscript
{
public const int GS_ARG_ENCODING_LOCAL = 0;
public const int GS_ARG_ENCODING_UTF8 = 1;
[DllImport("gsdll32.dll")]
private static extern int gsapi_new_instance(out IntPtr inst, IntPtr handle);
[DllImport("gsdll32.dll")]
private static extern int gsapi_set_arg_encoding(IntPtr inst, int encoding);
[DllImport("gsdll32.dll")]
private static extern int gsapi_init_with_args(IntPtr inst, int argc, IntPtr[] argv);
[DllImport("gsdll32.dll")]
private static extern int gsapi_exit(IntPtr inst);
[DllImport("gsdll32.dll")]
private static extern void gsapi_delete_instance(IntPtr inst);
private static void checkReturnValue(int retval)
{
if (retval != 0)
throw ...; // implement error handling here
}
public static void run(string[] argv)
{
IntPtr inst;
checkReturnValue(gsapi_new_instance(out inst, IntPtr.Zero));
try
{
IntPtr[] utf8argv = new IntPtr[argv.length];
for (int i=0; i<utf8argv.Length; i++)
utf8argv[i] = NativeUtf8FromString(argv[i]);
try
{
checkReturnValue(gsapi_set_arg_encoding(inst, GS_ARG_ENCODING_UTF8));
checkReturnValue(gsapi_init_with_args(inst, utf8argv.Length, utf8argv));
checkReturnValue(gsapi_exit(inst));
finally
{
for (int i=0; i<utf8argv.Length; i++)
Marshal.FreeHGlobal(utf8argv[i]);
}
}
finally
{
gsapi_delete_instance(inst);
}
}
}

Related

Create C++ dll with functions whose arguments can be called as out parameter in c#

I want to create a function in c++ that takes two parameter(char[], int) and modifies the parameters(Similar to out parameter in c#) and then create a dll that can be used in c#.
C++ Sample Code:
static void funct(char * name, int size)
{
char[] testName="John";
name=&testName;
size=5;
}
C# Sample Code:
const string dllLocation = "D:\\Test.dll";
[DllImport(dllLocation, CallingConvention = CallingConvention.Cdecl)]
private static extern void funct(StringBuilder name, int size);
This is not correct code. It is just to give an idea of what I want. I want to use c# to access the c++ function through dll and obtain the name and size(no of characters).
Use pointers in the C++ side and marshal these by ref on the C# side.
static void funct(char** name, int* size)
{
char[] testName="John";
*name=&testName;
*size=5;
}
const string dllLocation = "D:\\Test.dll";
[DllImport(dllLocation, CallingConvention = CallingConvention.Cdecl)]
private static extern void funct(ref StringBuilder name, ref int size);
Beware with the char array, it may create memory leaks or worse crashes, it would be better to first test the size of the buffer and the size of the data you want to pass to C#, if there is enough room copy it, else inform to C# that it needs more size so it's allocated by C#.
Something like this:
static int funct(char** name, int* size, int bufferSize)
{
if(bufferSize < 4)
return 4;
char[] testName="John";
memcpy(name*, &char[0], 4);
*size=5;
return -1;
}
const string dllLocation = "D:\\Test.dll";
[DllImport(dllLocation, CallingConvention = CallingConvention.Cdecl)]
private static extern void funct(ref StringBuilder name, ref int size, int bufferSize);
StringBuilder sb = null;
int size = 0;
//Request size
int neededSize = funct(ref sb, ref size, 0);
//Create buffer with appropiate size
sb = new StringBuilder(neededSize);
//Call with the correct size, test result.
if(funct(ref sb, ref size, neededSize) != -1)
throw new Exception();

[GnuTLS Library in a C# project]

I am trying to import the GnuTLS library to my C# project and use its APIs. Unfortunately, I cannot find any way on how to do this with the C-based GnuTLS library.
Does anyone know a way on how to use the GnuTLS library in a C# project or even on how to use the Windows build of the GnuTLS library available on their website https://www.gnutls.org/download.html so that I can run it using a C compiler and use the P/Invoke in C# to access the necessary APIs.
(In C#, I tried to import the libraries as reference using MSVS2010 but it says that it is not a valid .NET assembly nor a COM component)
(Also tried the Windows build of this library using a simple C code that calls a function but fails on compilation due to an error "... undefined reference to ...". I put the header files in MinGW directory as well as the DLL and EXE files).
You can use gnutls via P\Invoke. So it's worked on unix platforms.
Example on linux:
namespace GnuTlsExample
{
internal static class NativeMethodsLinux {
internal enum GNUTLS_X509_FMT
{
GNUTLS_X509_FMT_DER = 0,
GNUTLS_X509_FMT_PEM = 1
}
[DllImport("libgnutls.so.30")]
internal static extern int gnutls_x509_crt_list_import(IntPtr certs, ref int cert_max, IntPtr data, GNUTLS_X509_FMT format, uint flags);
[DllImport("libgnutls.so.30")]
internal static extern int gnutls_x509_privkey_init(ref IntPtr key);
[DllImport("libgnutls.so.30")]
internal static extern int gnutls_x509_privkey_import(IntPtr key, IntPtr data, GNUTLS_X509_FMT format);
[DllImport("libgnutls.so.30")]
internal static extern int gnutls_certificate_set_x509_key(IntPtr cred, IntPtr certs, int max, IntPtr key);
[StructLayout(LayoutKind.Sequential)]
internal class gnutls_datum_t
{
public IntPtr data = IntPtr.Zero;
public int size = 0;
}
}
class Program
{
static void Main(string[] args)
{
var buf = ByteArrayToGnuTlsDatum(File.ReadAllBytes(certificateFilePath));
var certs = Marshal.AllocHGlobal(IntPtr.Size);
var max = 6;
var tlsCtx = IntPtr.Zero;
var isServer = 0;
var key = IntPtr.Zero;
var bufKey = MarshalUtils.ByteArrayToGnuTlsDatum(File.ReadAllBytes(keyFilePath));
var res = NativeMethodsLinux.gnutls_x509_privkey_init(ref key);
res = NativeMethodsLinux.gnutls_x509_privkey_import(key, bufKey,
NativeMethodsLinux.GNUTLS_X509_FMT.GNUTLS_X509_FMT_PEM);
res = NativeMethodsLinux.gnutls_x509_crt_list_import(certs, ref max, buf,
NativeMethodsLinux.GNUTLS_X509_FMT.GNUTLS_X509_FMT_PEM, 0);
var cred = Marshal.AllocHGlobal(IntPtr.Size);
res = NativeMethodsLinux.gnutls_certificate_set_x509_key(cred, certs, max, key);
}
internal static IntPtr ByteArrayToGnuTlsDatum(byte[] bytes)
{
var berPtr = Marshal.AllocHGlobal(Marshal.SizeOf<NativeMethodsLinux.gnutls_datum_t>());
var valPtr = Marshal.AllocHGlobal(bytes.Length);
Marshal.Copy(bytes,0,valPtr,bytes.Length);
Marshal.StructureToPtr(new NativeMethodsLinux.gnutls_datum_t
{
data = valPtr,
size = bytes.Length
}, berPtr, true);
return berPtr;
}
}
}

Marshaling an IntPtr[] inside a struct causes midiStream functions to bug out, but unrolling the array to a bunch of fields works

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!

Last arguments appear corrupted when calling native function

Working on a C# wrapper for a native (C) library. I have the following function prototype in the native library:
typedef struct _NativeObj * NativeObj;
typedef struct AnotherNativeObj * AnotherNative;
__declspec(dllimport) NativeObj createNativeObj (
AnotherNative * anotherNative,
FirstCallback firstCallback,
void * firstOpaque,
SecondCallback secondCallback,
void * secondOpaque,
ThirdCallback thirdCallback,
void * thirdOpaque,
const char * firstString,
const char * secondString,
const char * thirdString,
time_t timeout,
char * fourthString,
int firstInt,
int secondInt,
int thirdInt,
int fourthInt,
char * fifthString,
int fifthInt,
char * sixthString);
This is the declaration in the C# code:
public delegate int ThirdCallbackDelegate(...);
public const uint NO_TIMEOUT = 0;
private uint timeout = NO_TIMEOUT;
private string fourthString;
private uint firstInt = 0;
private bool secondInt = false;
private bool thirdInt = true;
private bool fourthInt = true;
private string fifthString;
private bool fifthInt = false;
public string sixthString { get; set; }
[DllImport("path\\to.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr createNativeObj(
IntPtr anotherNative,
FirstCallbackDelegate firstCallback,
IntPtr firstOpaque,
SecondCallbackDelegate secondCallback,
IntPtr secondOpaque,
ThirdCallbackDelegate thirdCallback,
IntPtr thirdOpaque,
string firstString,
string secondString,
string thirdString,
int timeout,
string fourthString,
int firstInt,
int secondInt,
int thirdInt,
int fourthInt,
string fifthString,
int fifthInt,
string sixthString);
And the logic behind the parameters:
IntPtr myOpaque = createNativeObj(IntPtr.Zero,
null,
IntPtr.Zero,
null,
IntPtr.Zero,
thirdCallbackDelegate,
IntPtr.Zero,
firstString,
secondString,
thirdString,
(int)timeout,
fourthString,
(int)firstInt,
Convert.ToInt32(secondInt),
Convert.ToInt32(thirdInt),
Convert.ToInt32(fourthInt),
fifthString,
Convert.ToInt32(fifthInt),
sixthString);
At runtime, right at the native function's start, the values for the arguments after timeout are corrupted.
On Windows, using MS tools, and assuming that you did not define _USE_32BIT_TIME_T, the time_t type is 8 bytes wide. Which means you need to declare it as long in your C# p/invoke code to match.
I suspect that your native library isn't using the __cdecl calling convention but something like __stdcall. In general it's best to not take any chances and enforce a calling convention at the native library level instead of letting the compiler or the project options determine it. Try this:
[DllImport("path\\to.dll", CallingConvention=CallingConvention.StdCall)]

How do I read the names from a PE module's export table?

I've successfully read a PE header from an unmanaged module loaded into memory by another process. What I'd like to do now is read the names of this module's exports. Basically, this is what I have so far (I've left out a majority of the PE parsing code, because I already know it works):
Extensions
public static IntPtr Increment(this IntPtr ptr, int amount)
{
return new IntPtr(ptr.ToInt64() + amount);
}
public static T ToStruct<T>(this byte[] data)
{
GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
T result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return result;
}
public static byte[] ReadBytes(this Process process, IntPtr baseAddress, int size)
{
int bytesRead;
byte[] bytes = new byte[size];
Native.ReadProcessMemory(process.Handle, baseAddress, bytes, size, out bytesRead);
return bytes;
}
public static T ReadStruct<T>(this Process process, IntPtr baseAddress)
{
byte[] bytes = ReadBytes(process, baseAddress, Marshal.SizeOf(typeof(T)));
return bytes.ToStruct<T>();
}
public static string ReadString(this Process process, IntPtr baseAddress, int size)
{
byte[] bytes = ReadBytes(process, baseAddress, size);
return Encoding.ASCII.GetString(bytes);
}
GetExports()
Native.IMAGE_DATA_DIRECTORY dataDirectory =
NtHeaders.OptionalHeader.DataDirectory[Native.IMAGE_DIRECTORY_ENTRY_EXPORT];
if (dataDirectory.VirtualAddress > 0 && dataDirectory.Size > 0)
{
Native.IMAGE_EXPORT_DIRECTORY exportDirectory =
_process.ReadStruct<Native.IMAGE_EXPORT_DIRECTORY>(
_baseAddress.Increment((int)dataDirectory.VirtualAddress));
IntPtr namesAddress = _baseAddress.Increment((int)exportDirectory.AddressOfNames);
IntPtr nameOrdinalsAddress = _baseAddress.Increment((int)exportDirectory.AddressOfNameOrdinals);
IntPtr functionsAddress = _baseAddress.Increment((int)exportDirectory.AddressOfFunctions);
for (int i = 0; i < exportDirectory.NumberOfFunctions; i++)
{
Console.WriteLine(_process.ReadString(namesAddress.Increment(i * 4), 64));
}
}
When I run this, all I get is a pattern of double question marks, then completely random characters. I know the header is being read correctly, because the signatures are correct. The problem has to lie in the way that I'm iterating over the function list.
The code at this link seems to suggest that the names and ordinals form a matched pair of arrays, counted up to NumberOfNames, and that the functions are separate. So your loop may be iterating the wrong number of times, but that doesn't explain why you're seeing bad strings from the very beginning.
For just printing names, I'm having success with a loop like the one shown below. I think the call to ImageRvaToVa may be what you need to get the correct strings? However I don't know whether that function will work unless you've actually loaded the image by calling MapAndLoad -- that's what the documentation requests, and the mapping did not seem to work in some quick experiments I did using LoadLibrary instead.
Here's the pInvoke declaration:
[DllImport("DbgHelp.dll", CallingConvention = CallingConvention.StdCall), SuppressUnmanagedCodeSecurity]
public static extern IntPtr ImageRvaToVa(
IntPtr NtHeaders,
IntPtr Base,
uint Rva,
IntPtr LastRvaSection);
and here's my main loop:
LOADED_IMAGE loadedImage = ...; // populated with MapAndLoad
IMAGE_EXPORT_DIRECTORY* pIID = ...; // populated with ImageDirectoryEntryToData
uint* pFuncNames = (uint*)
ImageRvaToVa(
loadedImage.FileHeader,
loadedImage.MappedAddress,
pIID->AddressOfNames,
IntPtr.Zero);
for (uint i = 0; i < pIID->NumberOfNames; i++ )
{
uint funcNameRVA = pFuncNames[i];
if (funcNameRVA != 0)
{
char* funcName =
(char*) (ImageRvaToVa(loadedImage.FileHeader,
loadedImage.MappedAddress,
funcNameRVA,
IntPtr.Zero));
var name = Marshal.PtrToStringAnsi((IntPtr) funcName);
Console.WriteLine(" funcName: {0}", name);
}
}

Categories