using UpdateResource() with PInvoke

  • Thread starter Thread starter tsahiasher
  • Start date Start date
T

tsahiasher

hi,
i'm trying to use the Win32 API UpdateResource function to add a file
to an exe file, but somehow i'm getting a NullReferenceException when i
call the function. here is a piece of the code:

GCHandle gch = GCHandle.Alloc(fileBuffComp);
if (UpdateResource(hResource, "FILE", fileName, MakeLangId(0x09,
0x01),
/* */(IntPtr)gch, compFileLen) == false) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}

where fileBuffComp is a byte array containing the file, after i read it
from disk (and compressed it with #ZipLib). the function is declared
like this:

[DllImport("kernel32.dll", SetLastError=true)]
static extern bool UpdateResource(IntPtr hUpdate, String lpType,
String lpName,
ushort wLanguage, IntPtr lpData, uint cbData);

any ideas?
 
[DllImport("kernel32.dll", SetLastError=true)]
static extern bool UpdateResource(IntPtr hUpdate, String lpType,
String lpName,
ushort wLanguage, IntPtr lpData, uint cbData);

Change this to

.... ushort wLanguage, byte[] lpData, uint cbData);

and then pass in fileBuffComp directly, and get rid of the GCHandle.


Mattias
 
this solved the exception, but the file is not added to the file. are
you sure this is correct? the byte array is managed memory, which can
be moved around by the garbage collector, while the API is unmanaged
and normally expects a pointer to a buffer.
 
i even tried this:

GCHandle gch = GCHandle.Alloc(fileBuffComp);
unsafe {
if (UpdateResource(hResource, "FILE", fileName,
MakeLangId(0x09, 0x01),
/* */((IntPtr)gch).ToPointer(), compFileLen) ==
false) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}


with the declaration

[DllImport("kernel32.dll", SetLastError=true)]
static extern unsafe bool UpdateResource(IntPtr hUpdate, String
lpType, String lpName,
ushort wLanguage, void *lpData, uint cbData);

where the lpData is exactly what it is in the API, and it doesn't work.
i have a similar problem elswhere, where i try to remove a resource by
sending null to lpData, and it doesn't work either.
 
Back
Top