Rank: Administration
Groups: AcademicCoachingSchool, admin, Administration, BookSeller, CatholicSchool, CoachingAdult, CoachingProfessional, CoachingSports, ExtraCurriculumCoaching, IndependentSchool, Moderator, MusicTeacher, PrivateSchool, PublicSchool, SelectiveSchool, tutor Joined: 23/11/2008(UTC) Posts: 523
|
Call unmanaged code with int* or char* using simple DllImport As discussed in How to call native C/C++ functions with pointers' parameters from C#, we can use Platform Invoke or DllImport to call native/unmanaged code with flat C API from a .NET application (eg. in C#). P/Invoke can be very simple when only the isomorphic types are used as parameters in the exported functions of the native dll. The isomorphic types such as "int" in C# and C++ is identical. However, when the parameters of the function involve non-isomorhic types such as char* or int*, we need to do a bit more. For example, for char*, we must allocate char* buffer and receive string by pointer, we cannot use UnmanagedType.LPStr attribute, so we pass ANSI string as byte array. int* is more simple because it's 1-element Int32 array. See the following example: Code:using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
[DllImport("decrypt.dll", EntryPoint = "_GetSerialRegData"/*,
ExactSpelling = false*/,SetLastError=true)]
static extern void GetSerialRegData(
[MarshalAs(UnmanagedType.LPArray)] Int32[] Salt,
[MarshalAs(UnmanagedType.LPArray)] byte[] SerialNo,
[MarshalAs(UnmanagedType.LPArray)] byte[] ModId,
[MarshalAs(UnmanagedType.LPArray)] Int32[] Days,
[MarshalAs(UnmanagedType.LPArray)] Int32[] Qty, string SCode);
public static void Main(string[] args)
{
byte[] SerialNo = new byte[6];
byte[] ModId = new byte[6];
Int32[] Salt = new Int32[1];
Int32[] Days = new Int32[1];
Int32[] Qty = new Int32[1];
Salt[0] = 0;
Days[0] = 0;
Qty[0] = 0;
string SCode = "BKXP8T3BXVRWUSAV77FDG";
GetSerialRegData(Salt, SerialNo, ModId, Days, Qty, SCode);
string strSerial = System.Text.Encoding.ASCII.GetString(SerialNo);
string strModId = System.Text.Encoding.ASCII.GetString(ModId);
int nSalt = Salt[0];
int nDays = Days[0];
int nQty = Qty[0];
}
}
}
In the example, I allocated 6 bytes for receiving each ANSI string, one element in Int32 array. For receiving string from byte array I used Text.Encoding.ASCII class. Edited by user Tuesday, 4 December 2018 7:50:48 AM(UTC)
| Reason: Not specified
|