C++简单封装C#类库及调用

记录

c#创建类库工程

using System;
using System.Collections.Generic;
using System.Text;
using Advantech.Adam;
using System.Runtime.InteropServices;
using System.Net.Sockets;

namespace Adam6060Com
{
    [ComVisible(true)]
    [Guid("88DE7087-8B80-4978-B2F4-C0937984A078")]
    public interface DoAdam6060
    {
        [DispId(1)]
        void Adam6060Init(string m_IP, int m_Port);

        [DispId(2)]
        void Adam6060SingleSetOut(int m_out, bool status);

        [DispId(3)]
        bool Adam6060ReadStatus(int m_in);
    }

    [ComVisible(true)]
    [Guid("1AA8315B-C1A3-45C1-A9E0-9D2CC43763A1")]
    public class Adam6060Operate : DoAdam6060
    {
        private AdamSocket adamModbus;

        public void Adam6060Init(string m_IP, int m_Port)
        {
            adamModbus = new AdamSocket();
            adamModbus.SetTimeout(1000, 1000, 1000); // set timeout for TCP
            if (adamModbus.Connect(m_IP, ProtocolType.Tcp, m_Port))
            {
                Console.WriteLine("Adam6060 Init Sucess");
            }
            else
            {
                Console.WriteLine("Adam6060 Init Fail");
            }
        }

        public void Adam6060SingleSetOut(int m_out, bool status)
        {
            adamModbus.Modbus().ForceSingleCoil(m_out + 17, status);		//控制输出通断17-22/0-1
        }

        public bool Adam6060ReadStatus(int m_in)
        {
            bool res = false;
            bool[] bWDT;
            adamModbus.Modbus().ReadCoilStatus(1, 6, out bWDT);
            res = bWDT[m_in];
            return res;
        }
    }
}

C++测试

#include <iostream>
#include <Windows.h>
//#import "AdamCom.tlb"
//using namespace AdamCom;
//
//int main() {
//	CoInitialize(NULL);
//	//AdamCom::DoAdamPtr ptr(__uuidof(DoAdam));
//
//	CLSID clsid;
//	HRESULT hr = CLSIDFromProgID(OLESTR("AdamCom.AdamOperate"), &clsid);
//	DoAdam *ptr;
//	hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER, __uuidof(DoAdam), (LPVOID*)&ptr);
//
//	std::cout << ptr->Plus(1, 2);
//	CoUninitialize();
//
//	system("pause");
//	return 0;
//}
#import "Adam6060Com.tlb"

int main() {
	CoInitialize(NULL);

	CLSID clsid;
	HRESULT hr = CLSIDFromProgID(OLESTR("Adam6060Com.Adam6060Operate"), &clsid);
	Adam6060Com::DoAdam6060 *ptr;
	hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER, __uuidof(Adam6060Com::DoAdam6060), (LPVOID*)&ptr);
	ptr->Adam6060Init("192.168.1.5", 502);
	CoUninitialize();
	system("pause");
	return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值