C#调用C函数的方法

发育商
Process p = new Process();
p.StartInfo.FileName = "sh";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine("ifconfig eth0 192.168.1.18 netmask 255.255.255.0 ");
p.StandardInput.WriteLine("exit");
string strResult = p.StandardOutput.ReadToEnd();
TextBox1.Text = strResult;
p.Close();
C#调用C函数的方法:
方法一:
1.新建Visual C++类型的Win32项目
C语言的函数定义如下:
extern "C" __declspec(dllexport) int fnTestWin32(void);
实现如下
extern "C" __declspec(dllexport) int fnTestWin32(void)
{
return 42;
}
工程属性页[常规]->[配置类型]选择[动态库.dll]
会生成.lib和.dll文件。用Dependency工具能看到fnTestWin32函数,因为使用了extern "C"
2.C#工程中
[DllImport("TestWin32.dll", EntryPoint = "fnTestWin32", CharSet = CharSet.Ansi)]
private static extern int fnTestWin32();
把Win32项目生成的dll拷贝到C#生成的exe文件,就可以调用了。
方法二:
1.新建Win32工程
直接使用C语言,函数定义不使用extern "C" __declspec(dllexport)
工程属性页[常规]->[配置类型]选择[静态库(.lib)]
2.新建Visual C++ CLR 类库工程
这里面写的是C++的类,提供给C#直接调用的,作为C与C#的中转,主要使用Marshal类应用上面的Win32工程,并包含头文件
extern "C"
{
#include "app_notify.h"
}
3.C#工程中直接使用CLR类库工程生成的dll
#include <stdio.h>;
#include <string.h>;这样紫啊
#include <unistd.h>;
#include <sys/socket.h>;
#include <sys/types.h>;
#include <sys/param.h>;
#include <sys/ioctl.h>;
#include <net/if.h>;
#include <netinet/in.h>;
#include <netinet/ip.h>;
#include <net/if_arp.h>;
#include <arpa/inet.h>;
网络流量测试
#include <netdb.h>;
#include <error.h>;
#include <stdlib.h>;
#include <fcntl.h>;
int setlocalip(char *ip)
{
register int fd, intrface;
struct ifreq buf[8];
struct ifconf ifc;
char oldip[16];
struct sockaddr_in addr;
if (ip == NULL)
return -1;
if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >;= 0) { ifc.ifc_len = sizeof buf;
慢性病ifc.ifc_buf = (caddr_t) buf;
if (!ioctl (fd, SIOCGIFCONF, (char *) &ifc)) {
intrface = ifc.ifc_len / sizeof (struct ifreq);
while (intrface-- >; 0)
{
if (strcmp(buf[intrface].ifr_name, "lo") == 0) continue;
/*Get IP of the net card */
拟合优度
if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[intrface])))
钓水鬼{
memset(oldip, 0, sizeof(oldip));
sprintf(oldip, "%s", (char*)inet_ntoa(((struct sockaddr_in*)(&buf[intrface ].ifr_addr ))->;sin_addr));
printf("oldip is %s\n", oldip);
((struct sockaddr_in*)(&buf[intrface].ifr_addr))->;sin_addr.s_addr = inet_addr(ip); if (ioctl(fd, SIOCSIFADDR, (char *)&buf[intrface]))
printf("set ip error\n");
}
else {
sprintf (ip, "get ip error");
}
}
}
}
close (fd);
return 0;
}

本文发布于:2024-09-21 00:37:13,感谢您对本站的认可!

本文链接:https://www.17tex.com/xueshu/612849.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:工程   使用   函数   类型   调用   选择   定义   生成
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议