C# 調用C/C++ Dll(參數含char*指針,返回char*指針)

動態庫:


//MyPointDll.h
extern"C" _declspec(dllexport) char* strcpyTest(char* dest,char* sour);

// MyPointDll.cpp : 定義 DLL 應用程序的導出函數。
//

#include "stdafx.h"
#include "MyPointDll.h"

char* strcpyTest(char* dest,char* sour)
{ 
char* temp = dest;
while('\0' != *sour)
{
*dest = *sour;
dest++;
sour++;
}
*dest = '\0';
return temp;
}


C#調用Dll:


using System;
using System.Runtime.InteropServices;

namespace CSCallMyPointDll
{
    class Program
    {

        [DllImport(@"MyPointDll.dll", EntryPoint = "strcpyTest", CallingConvention = CallingConvention.Cdecl/*, CallingConvention = CallingConvention.Cdecl*/)]

        public static extern IntPtr strcpyTest(ref byte dest, string sour);

        static void Main(string[] args)
        {
            string strSour = "CS Call C Point Dll!";

            Byte[] bPara = new Byte[100];    //新建字節數組

            IntPtr pRet = strcpyTest(ref bPara[0], strSour);
            string strGet = System.Text.Encoding.Default.GetString(bPara, 0, bPara.Length);    //將字節數組轉換爲字符串
            string strRet = Marshal.PtrToStringAnsi(pRet);

            Console.WriteLine("源字符串:");
            Console.WriteLine(strSour);

            Console.WriteLine("傳出值:");
            Console.WriteLine(strGet);

            Console.WriteLine("返回值:");
            Console.WriteLine(strRet);
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章