Click here to Skip to main content
15,667,422 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I am very new to C# and C/C++. I wrote a code in C that stored 2 variables in an array and return the array. Using the P/invoke method I created a DLL library of this C function and imported the library to C#. While calling array, I am unable to get the array from the C#.
Need your kind help. here is C code
<pre>#include <stdio.h>

extern __declspec(dllexport) int* sum();
int* sum()
    int a = 50, b = 80, sum, neg;
    sum = a + b;
    neg = b - a;
    int arr[2] = { sum, neg };
    return arr;

Now the C# code is...
using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication
    class Program
        unsafe public static extern int* sum();
        static void Main(string[] args)
                int* array2 = sum();

                Console.WriteLine("Value: " + array2[0]);

Please let me know how can I get array.

What I have tried:

I am new to coding so I tried things since I haven't experience in C# and C so couldn't get results.
Updated 24-Dec-21 19:26pm
honey the codewitch 24-Dec-21 19:54pm    
It's because you're using cdecl as your calling convention. And how is C# supposed to know the size of your array? You'll have an easier type using stdcall as your calling convention, and yielding an out pointer to the array and an out pointer to the size of the array for your function.

your C++ code is invalid anyway. Anything you declared in the function goes away once the function is complete, meaning you're returning a bad pointer.

Also using unsafe code in C# is inadvisable, because unless something changed, it tends to require full trust, so it won't run unless it's installed in a particular way on the target machine.

I'm going to be very frank with you. You are swimming way out of your depth right now. Learn C#. Learn C++. Then learn how to use them together. Right now you don't know any of them, except maybe some C# from the looks of things.
suleman Ali kazmi 25-Dec-21 1:25am    
Thanks for helping me out. Is it possible if you provide me an example. Actually I am very new in this stuff. Thanks
honey the codewitch 25-Dec-21 1:28am    
You're not hearing me. Even if I provided you an example, you would not understand it, and so it wouldn't benefit you. If you were to use it, you could not maintain that code, and I'm not going to maintain it for you.

Therefore I will not give you that. It would be like giving someone my loaded gun.

This is not something you should be trying before you even understand even the basics of how to code C++. Learn how to code some C++ first.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900