BadImageFormatException: PInvoke ImportDll with hdf5dll.dll

孤人 提交于 2021-02-16 20:11:05

问题


Ok, I have the HDF5 library downloaded from the official site, and I have a few DLLs, including hdf5dll.dll, and hdf5_hldll.dll.

I have what I think to be some wrappers around the native calls, in my classes H5, H5LT, H5F, and H5T. Example from H5.cs:

namespace HDF5
{
    using hid_t = System.Int32;
    using herr_t = System.Int32;
    using hsize_t = System.UInt64;
    using size_t = System.UInt32;
    // hbool_t is 0:false, +:true
    using hbool_t = System.UInt32;
    // htri_t is 0:false, +:true, -:failure
    using htri_t = System.Int32;

    public class H5
    {
        const CharSet StringMarshallingType = CharSet.Ansi;
        const string DLLNAME = "hdf5dll.dll";

        ///* Functions in H5.c */
        //H5_DLL herr_t H5open(void);
        [DllImport(DLLNAME,
            CharSet = StringMarshallingType)]
        public static extern herr_t H5open();

And in Program.cs, I use H5.H5open();, but I get a BadImageFormatException. Do I need a different DLL? Does the method signature look wrong?

I'd like to, as the next step, get this in C#: http://www.hdfgroup.org/HDF5/Tutor/h5lite.html .

OS: Windows 7 64 bit
Environment: Visual Studio 2008 Professional

Update: I don't know if this will be related, and I don't remember if my environment is VS2008 SP1, but this question may hold a key to solving the mystery. I am as of now trying to repeat the scenario on 32 bit VS 2010 at home.


回答1:


That happens when you're trying to run P/Invoke operations on a dll meant for x86 architecture from within an x64 process or vice versa. I'd check all of that and if they're out of sync, consider targeting the processor that HDF5 targets with your application, or checking if a processor-specific version is available.




回答2:


Looking at the documentation from here, the function prototype is:

herr_t H5open(void);

And also the DLLNAME is disallowed, you must explicitly specify the dll name - no questions asked.

The proper signature is:

[DllImport("hdf5dll.dll")]public static extern herr_t H5open();

Make sure you have the type herr_t defined...

Let the runtime take care of the marshalling for you....

Also make sure, the DLL is present in the same path as where the compiled .EXE (your code) is generated.

Edit: Thanks to the OP for pointing out my blooper....




回答3:


On x64 operatingsystems .net programs usually run in x64 mode. Just set your target processor architecture to x86 and try again. Just in Visual studio open your "Solution Configuration"-Manager and add a new target Platform.



来源:https://stackoverflow.com/questions/3471926/badimageformatexception-pinvoke-importdll-with-hdf5dll-dll

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!