Use windows C++ API in dotnet

U

Usman

Hi

Can someone please tell me how to use C++ API in c# code. Like I have to use
the functionality of memcpy in my C# code. I have to copy the bytes of an
integer variable to 4 character bytes to convert it to string, if there's
any alternative to this in C#, please recommend otherwise tell me how can I
use memcpy itself in C# code.

Regards

Usman Jamil
 
A

adebaene

Usman said:
Hi

Can someone please tell me how to use C++ API in c# code. Like I have to use
the functionality of memcpy in my C# code. I have to copy the bytes of an
integer variable to 4 character bytes to convert it to string, if there's
any alternative to this in C#, please recommend otherwise tell me how can I
use memcpy itself in C# code.

First of all, there is no C++ Windows API (with the marginal exception
of GDI+) : All the Windows native API is C, not C++.

Next, memcpy is a CRT API, it is not part of the Windows API (whereas
RTLCopyMemory is).

To finish with, in your particular case, your best bet is to use the
BitConverter.GetBytes method.

Arnaud
MVP - VC
 
B

Ben Voigt

Usman said:
Hi

Can someone please tell me how to use C++ API in c# code. Like I have to
use
the functionality of memcpy in my C# code. I have to copy the bytes of an
integer variable to 4 character bytes to convert it to string, if there's
any alternative to this in C#, please recommend otherwise tell me how can
I
use memcpy itself in C# code.

For Win32 API, like CopyMemory, see http://pinvoke.net
The pure .NET version is System.Runtime.InteropServices.Marshal.Copy (still
requires unmanaged code permission).

However, for your need, I don't think CopyMemory is going to help you (it's
the exact windows analogue to the ANSI C runtime function memcpy).

If you are ok with using the machine byte ordering, you can just use an
unsafe code block and cast a pointer (simplest, fastest).
For verifiability,
create a MemoryStream
use a BinaryWriter to write your data
use the MemoryStream's ToArray() method to get the raw bytes.

In reverse, you can construct a memory stream from an array of bytes, then
use BinaryReader to get back typed variabled.

However, this seems very expensive.

Does anyone know of any method for doing this in verifiable code (not
expecting to see the insides of references, only value types) without
creating a bunch of extra objects? I know you could reuse the same
BinaryWriter/MemoryStream by calling Seek(), but it will still allocate a
new byte[] for each call to ToArray, right?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top