Проверьте, является ли неуправляемый DLL 32-разрядным или 64-разрядным?

Как предложено Владиславом Скумалом , попробуйте этот метод:

public Bitmap drawTextToBitmap(Context mContext,  int resourceId,  String mText) {
    try {
         Resources resources = mContext.getResources();
         float scale = resources.getDisplayMetrics().density;
         Bitmap bitmap = BitmapFactory.decodeResource(resources, resourceId);
         android.graphics.Bitmap.Config bitmapConfig =   bitmap.getConfig();
         // set default bitmap config if none
         if(bitmapConfig == null) {
           bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
         }
         // resource bitmaps are imutable,
         // so we need to convert it to mutable one
         bitmap = bitmap.copy(bitmapConfig, true);

         Canvas canvas = new Canvas(bitmap);
         // new antialised Paint
         Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
         // text color - #3D3D3D
         paint.setColor(Color.rgb(110,110, 110));
         // text size in pixels
         paint.setTextSize((int) (12 * scale));
         // text shadow
         paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY);

         // draw text to the Canvas center
         Rect bounds = new Rect();
         paint.getTextBounds(mText, 0, mText.length(), bounds);
         int x = (bitmap.getWidth() - bounds.width())/6;
         int y = (bitmap.getHeight() + bounds.height())/5;

         canvas.drawText(mText, x * scale, y * scale, paint);

         return bitmap;
    } catch (Exception e) {
        // TODO: handle exception

        return null;
    }

}

назовите этот метод

Bitmap bmp =drawTextToBitmap(this,R.drawable.aa,"Hello Android");
img.setImageBitmap(bmp);

на выходе

enter image description here

43
задан Peter Mortensen 28 June 2015 в 13:37
поделиться

3 ответа

Refer to the specifications. Here's a basic implementation:

public static MachineType GetDllMachineType(string dllPath)
{
    // See http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx
    // Offset to PE header is always at 0x3C.
    // The PE header starts with "PE\0\0" =  0x50 0x45 0x00 0x00,
    // followed by a 2-byte machine type field (see the document above for the enum).
    //
    FileStream fs = new FileStream(dllPath, FileMode.Open, FileAccess.Read);
    BinaryReader br = new BinaryReader(fs);
    fs.Seek(0x3c, SeekOrigin.Begin);
    Int32 peOffset = br.ReadInt32();
    fs.Seek(peOffset, SeekOrigin.Begin);
    UInt32 peHead = br.ReadUInt32();

    if (peHead!=0x00004550) // "PE\0\0", little-endian
        throw new Exception("Can't find PE header");

    MachineType machineType = (MachineType) br.ReadUInt16();
    br.Close();
    fs.Close();
    return machineType;
}

The MachineType enum is defined as:

public enum MachineType : ushort
{
    IMAGE_FILE_MACHINE_UNKNOWN = 0x0,
    IMAGE_FILE_MACHINE_AM33 = 0x1d3,
    IMAGE_FILE_MACHINE_AMD64 = 0x8664,
    IMAGE_FILE_MACHINE_ARM = 0x1c0,
    IMAGE_FILE_MACHINE_EBC = 0xebc,
    IMAGE_FILE_MACHINE_I386 = 0x14c,
    IMAGE_FILE_MACHINE_IA64 = 0x200,
    IMAGE_FILE_MACHINE_M32R = 0x9041,
    IMAGE_FILE_MACHINE_MIPS16 = 0x266,
    IMAGE_FILE_MACHINE_MIPSFPU = 0x366,
    IMAGE_FILE_MACHINE_MIPSFPU16 = 0x466,
    IMAGE_FILE_MACHINE_POWERPC = 0x1f0,
    IMAGE_FILE_MACHINE_POWERPCFP = 0x1f1,
    IMAGE_FILE_MACHINE_R4000 = 0x166,
    IMAGE_FILE_MACHINE_SH3 = 0x1a2,
    IMAGE_FILE_MACHINE_SH3DSP = 0x1a3,
    IMAGE_FILE_MACHINE_SH4 = 0x1a6,
    IMAGE_FILE_MACHINE_SH5 = 0x1a8,
    IMAGE_FILE_MACHINE_THUMB = 0x1c2,
    IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x169,
}

I only needed three of these, but I included them all for completeness. Final 64-bit check:

// Returns true if the dll is 64-bit, false if 32-bit, and null if unknown
public static bool? UnmanagedDllIs64Bit(string dllPath)
{
    switch (GetDllMachineType(dllPath))
    {
        case MachineType.IMAGE_FILE_MACHINE_AMD64:
        case MachineType.IMAGE_FILE_MACHINE_IA64:
            return true;
        case MachineType.IMAGE_FILE_MACHINE_I386:
            return false;
        default:
            return null;
    }
}
46
ответ дан 26 November 2019 в 22:56
поделиться

Еще проще: посмотрите класс System.Reflection.Module. Он включает метод GetPEKind, который возвращает 2 перечисления, описывающих тип кода и целевой ЦП. Больше никакого шестнадцатеричного изображения!

(остальная часть этого очень информативного поста была бессовестно скопирована с http://www.developersdex.com/vb/message.asp?p=2924&r=6413567 )

Пример кода:

Assembly assembly = Assembly.ReflectionOnlyLoadFrom(@"<assembly Path>");
PortableExecutableKinds kinds;
ImageFileMachine imgFileMachine;
assembly.ManifestModule.GetPEKind(out kinds, out imgFileMachine);

PortableExecutableKinds можно использовать для проверки того, какой тип сборки. Это имеет 5 значений:

ILOnly: исполняемый файл содержит только промежуточный язык Microsoft. (MSIL) и поэтому нейтрален по отношению к 32- или 64-битным платформы.

NotAPortableExecutableImage: файл не находится в переносимом исполняемом файле (PE) формат файла.

PE32Plus: исполняемый файл требует 64-битной платформы.

Required32Bit: Исполняемый файл может быть запущен на 32-битной платформе или в 32-разрядная среда Windows в Windows (WOW) на 64-разрядной платформе.

Unmanaged32Bit: исполняемый файл содержит чистый неуправляемый код.

Ниже приведены ссылки:

Метод Module.GetPEKind: http://msdn.microsoft.com/en-us/library/system.reflection.module.getpekind.aspx

Перечисление PortableExecutableKinds: http://msdn.microsoft.com/en-us/library/system.reflection.portableexecutablekinds (VS.80) .aspx

Перечисление ImageFileMachine: http://msdn.microsoft.com/en-us/library/system.reflection.imagefilemachine.aspx

5
ответ дан 26 November 2019 в 22:56
поделиться

При использовании командной строки Visual Studio dumpbin /headers dllname.dll также работает.На моей машине в начале выхода указано:

FILE HEADER VALUES
8664 machine (x64)
5 number of sections
47591774 time date stamp Fri Dec 07 03:50:44 2007
21
ответ дан 26 November 2019 в 22:56
поделиться
Другие вопросы по тегам:

Похожие вопросы: