C# 调用C/C++ Dll(参数含char*指针,返回char*指针)

本文介绍了一个简单的C#调用C语言DLL的例子,展示了如何通过C#代码调用一个C语言编写的字符串复制函数。该示例涵盖了DLL导出函数的定义、C#中的DllImport声明以及调用过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

动态库:


//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);
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值