Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

268
Visualizações
How to make this code safe when accessing DLL?

To return arrays in C pointers needed. To clarify my question, I created a simple .c function and compiled as DLL and accessing it by C#. The C function is:

#include <stdio.h>

__declspec(dllexport) int* ReturnArray(int size) {

    int* arr = malloc(size * sizeof(int)); 

    arr[0] = 19;
    arr[1] = 18;
    arr[2] = 17;
    arr[3] = 16;
    arr[4] = 15;

    return arr;
}

On the C# side:

namespace ConsoleC2CSExample
{
    class Program
    {
        [DllImport("array.dll", EntryPoint = "ReturnArray", CallingConvention = CallingConvention.Cdecl)]
        public unsafe static extern short* ReturnArray(int size);
        static unsafe void Main(string[] args)
        {
            int arraySize = 5;

            short *ptr = ReturnArray(arraySize);
            
            for(int i = 0; i < arraySize; i++)
                Console.WriteLine(*(ptr + i * sizeof(short)));              

            Console.Read();
        }
    }
}

And the output is as expected as follows:

enter image description here

I have two questions here.

  1. How can this be done by not using unsafe mode?
  2. And what are the dangers if any of using unsafe?
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

C#/.NET is so-called managed code because it runs safely on the common language runtime (CLR). Whereas, C code is so-called unmanaged code.

The CLR ensures, that we will not suffer the typical problems known from C code (like buffer underflow, buffer overflow, ...) resulting in vulnerable code, crashing applications, unknown behavior, etc.

So the danger of using unsafe code is, that errors in your C library will probably terminate your entire C#/.NET application unexpectedly, causing you a lot of headache.

To get at least rid of the unsafe context within your C# code, you can try the following:

using System.Runtime.InteropServices;

namespace ConsoleC2CSExample
{
    class Program
    {
        [DllImport("array.dll", EntryPoint = "ReturnArray", CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr ReturnArray(int size);

        static void Main(string[] args)
        {
            int arraySize = 5;

            IntPtr ptr = ReturnArray(arraySize);
            
            for(int i = 0; i < arraySize; i++)
                Console.WriteLine(Marshal.ReadInt32(ptr + i * sizeof(int)));

            Console.Read();
        }
    }
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda