使用pbc

windows 下使用MinGW编译PBC库 Linux下编译PBC库很简单,在PBC Manual中有其介绍,PBC库本身是基于Linux环境来编写的,编译过程和普通其他库的编译过程一样: 1)./configure 2)make 3)make install 4)make clean 这里要注意一下,PBC库是基于GMP库的,如果Linux系统不存在GMP库时,在./configure这步时会出错,提示没有找到GMP库~~所以我 阅读详情


1环境

Linux CentOS 7
lua 5.3.1


pbc
GITHUB : https://github.com/cloudwu/pbc
WIKI : http://blog.codingnow.com/2011/12/protocol_buffers_for_c.html


2修改enum类型

将云风的pbc应用到项目中,修改了enum为数字类型,在pbc源码的binding/lua53/pbc-lua53.c 中的


binding/lua53/pbc-lua53.c

static void   
push_value(lua_State *L, int type, const char * type_name, union pbc_value *v) {
    switch(type) {
    case PBC_FIXED32:
    case PBC_INT:
        lua_pushinteger(L, (int)v->i.low);
        break;
    case PBC_REAL:
        lua_pushnumber(L, v->f);
        break;
    case PBC_BOOL:
        lua_pushboolean(L, v->i.low);
        break;
    case PBC_ENUM:                                                                                                                                                                           
        //lua_pushstring(L, v->e.name);
        lua_pushinteger(L, v->e.id);
        break;
    case PBC_BYTES:
    case PBC_STRING:
        lua_pushlstring(L, (const char *)v->s.buffer , v->s.len);
        break;
    case PBC_MESSAGE:
...


将binding/lua53/pbc-lua53.c中与PBC_ENUM相关的函数都改为使用int

binding/lua53/pbc-lua53.c

--[[                 
#define PBC_INT 1 
#define PBC_REAL 2
#define PBC_BOOL 3
#define PBC_ENUM 4
#define PBC_STRING 5
#define PBC_MESSAGE 6
#define PBC_FIXED64 7
#define PBC_FIXED32 8
#define PBC_BYTES 9
#define PBC_INT64 10
#define PBC_UINT 11
#define PBC_UNKNOWN 12
#define PBC_REPEATED 128
]]                   
                     
_reader[1] = function(msg) return _reader.int end 
_reader[2] = function(msg) return _reader.real end 
_reader[3] = function(msg) return _reader.bool end 
--_reader[4] = function(msg) return _reader.string end
_reader[4] = function(msg) return _reader.int end 
_reader[5] = function(msg) return _reader.string end 
_reader[6] = function(msg)
    local message = _reader.message
    return  function(self,key)
            return message(self, key, msg)
        end          
end    
...


3重新编译动态库

pbc/
make
pbc/binding/lua53
make

得到protobuf.so

如下图所示




4 测试用例

修改后的protobuf.lua
local c = require "protobuf.c"

local setmetatable = setmetatable
local type = type
local table = table
local assert = assert
local pairs = pairs
local ipairs = ipairs
local string = string
local print = print
local io = io
local tinsert = table.insert
local rawget = rawget

local M = {}

local _pattern_cache = {}

local P,GC

P = debug.getregistry().PROTOBUF_ENV

if P then
	GC = c._gc()
else
	P= c._env_new()
	GC = c._gc(P)
end

M.GC = GC

function M.lasterror()
	return c._last_error(P)
end

local decode_type_cache = {}
local _R_meta = {}

function _R_meta:__index(key)
	local v = decode_type_cache[self._CType][key](self, key)
	self[key] = v
	return v
end

local _reader = {}

function _reader:real(key)
	return c._rmessage_real(self._CObj , key , 0)
end

function _reader:string(key)
	return c._rmessage_string(self._CObj , key , 0)
end

function _reader:bool(key)
	return c._rmessage_int(self._CObj , key , 0) ~= 0
end

function _reader:message(key, message_type)
	local rmessage = c._rmessage_message(self._CObj , key , 0)
	if rmessage then
		local v = {
			_CObj = rmessage,
			_CType = message_type,
			_Parent = self,
		}
		return setmetatable( v , _R_meta )
	end
end

function _reader:int(key)
	return c._rmessage_int(self._CObj , key , 0)
end

function _reader:real_repeated(key)
	local cobj = self._CObj
	local n = c._rmessage_size(cobj , key)
	local ret = {}
	for i=0,n-1 do
		tinsert(ret,  c._rmessage_real(cobj , key , i))
	end
	return ret
end

function _reader:string_repeated(key)
	local cobj = self._CObj
	local n = c._rmessage_size(cobj , key)
	local ret = {}
	for i=0,n-1 do
		tinsert(ret,  c._rmessage_string(cobj , key , i))
	end
	return ret
end

function _reader:bool_repeated(key)
	local cobj = self._CObj
	local n = c._rmessage_size(cobj , key)
	local ret = {}
	for i=0,n-1 do
		tinsert(ret,  c._rmessage_int(cobj , key , i) ~= 0)
	end
	return ret
end

function _reader:message_repeated(key, message_type)
	local cobj = self._CObj
	local n = c._rmessage_size(cobj , key)
	local ret = {}
	for i=0,n-1 do
		local m = {
			_CObj = c._rmessage_message(cobj , key , i),
			_CType = message_type,
			_Parent = self,
		}
		tinsert(ret, setmetatable( m , _R_meta ))
	end
	return ret
end

function _reader:int_repeated(key)
	local cobj = self._CObj
	local n = c._rmessage_size(cobj , key)
	local ret = {}
	for i=0,n-1 do
		tinsert(ret,  c._rmessage_int(cobj , key , i))
	end
	return ret
end

--[[
#define PBC_INT 1
#define PBC_REAL 2
#define PBC_BOOL 3
#define PBC_ENUM 4
#define PBC_STRING 5
#define PBC_MESSAGE 6
#define PBC_FIXED64 7
#define PBC_FIXED32 8
#define PBC_BYTES 9
#define PBC_INT64 10
#define PBC_UINT 11
#define PBC_UNKNOWN 12
#define PBC_REPEATED 128
]]

_reader[1] = function(msg) return _reader.int end
_reader[2] = function(msg) return _reader.real end
_reader[3] = function(msg) return _reader.bool end
--_reader[4] = function(msg) return _reader.string end
_reader[4] = function(msg) return _reader.int end
_reader[5] = function(msg) return _reader.string end
_reader[6] = function(msg)
	local message = _reader.message
	return	function(self,key)
			return message(self, key, msg)
		end
end
_reader[7] = _reader[1]
_reader[8] = _reader[1]
_reader[9] = _reader[5]
_reader[10] = _reader[7]
_reader[11] = _reader[7]

_reader[128+1] = function(msg) return _reader.int_repeated end
_reader[128+2] = function(msg) return _reader.real_repeated end
_reader[128+3] = function(msg) return _reader.bool_repeated end
--_reader[128+4] = function(msg) return _reader.string_repeated end
_reader[128+4] = function(msg) return _reader.int_repeated end
_reader[128+5] = function(msg) return _reader.string_repeated end
_reader[128+6] = function(msg)
	local message = _reader.message_repeated
	return	function(self,key)
			return message(self, key, msg)
		end
end
_reader[128+7] = _reader[128+1]
_reader[128+8] = _reader[128+1]
_reader[128+9] = _reader[128+5]
_reader[128+10] = _reader[128+7]
_reader[128+11] = _reader[128+7]

local _decode_type_meta = {}

function _decode_type_meta:__index(key)
	local t, msg = c._env_type(P, self._CType, key)
	local func = assert(_reader[t],key)(msg)
	self[key] = func
	return func
end

setmetatable(decode_type_cache , {
	__index = function(self, key)
		local v = setmetatable({ _CType = key } , _decode_type_meta)
		self[key] = v
		return v
	end
})

local function decode_message( message , buffer, length)
	local rmessage = c._rmessage_new(P, message, buffer, length)
	if rmessage then
		local self = {
			_CObj = rmessage,
			_CType = message,
		}
		c._add_rmessage(GC,rmessage)
		return setmetatable( self , _R_meta )
	end
end

----------- encode ----------------

local encode_type_cache = {}

local function encode_message(CObj, message_type, t)
	local type = encode_type_cache[message_type]
	for k,v in pairs(t) do
		local func = type[k]
		func(CObj, k , v)
	end
end

local _writer = {
	real = c._wmessage_real,
	--enum = c._wmessage_string,
	enum = c._wmessage_int,
	string = c._wmessage_string,
	int = c._wmessage_int,
}

function _writer:bool(k,v)
	c._wmessage_int(self, k, v and 1 or 0)
end

function _writer:message(k, v , message_type)
	local submessage = c._wmessage_message(self, k)
	encode_message(submessage, message_type, v)
end

function _writer:real_repeated(k,v)
	for _,v in ipairs(v) do
		c._wmessage_real(self,k,v)
	end
end

function _writer:bool_repeated(k,v)
	for _,v in ipairs(v) do
		c._wmessage_int(self, k, v and 1 or 0)
	end
end

function _writer:string_repeated(k,v)
	for _,v in ipairs(v) do
		c._wmessage_string(self,k,v)
	end
end

function _writer:message_repeated(k,v, message_type)
	for _,v in ipairs(v) do
		local submessage = c._wmessage_message(self, k)
		encode_message(submessage, message_type, v)
	end
end

function _writer:int_repeated(k,v)
	for _,v in ipairs(v) do
		c._wmessage_int(self,k,v)
	end
end

_writer[1] = function(msg) return _writer.int end
_writer[2] = function(msg) return _writer.real end
_writer[3] = function(msg) return _writer.bool end
--_writer[4] = function(msg) return _writer.string end
_writer[4] = function(msg) return _writer.int end
_writer[5] = function(msg) return _writer.string end
_writer[6] = function(msg)
	local message = _writer.message
	return	function(self,key , v)
			return message(self, key, v, msg)
		end
end
_writer[7] = _writer[1]
_writer[8] = _writer[1]
_writer[9] = _writer[5]
_writer[10] = _writer[7]
_writer[11] = _writer[7]

_writer[128+1] = function(msg) return _writer.int_repeated end
_writer[128+2] = function(msg) return _writer.real_repeated end
_writer[128+3] = function(msg) return _writer.bool_repeated end
--_writer[128+4] = function(msg) return _writer.string_repeated end
_writer[128+4] = function(msg) return _writer.int_repeated end
_writer[128+5] = function(msg) return _writer.string_repeated end
_writer[128+6] = function(msg)
	local message = _writer.message_repeated
	return	function(self,key, v)
			return message(self, key, v, msg)
		end
end

_writer[128+7] = _writer[128+1]
_writer[128+8] = _writer[128+1]
_writer[128+9] = _writer[128+5]
_writer[128+10] = _writer[128+7]
_writer[128+11] = _writer[128+7]

local _encode_type_meta = {}

function _encode_type_meta:__index(key)
	local t, msg = c._env_type(P, self._CType, key)
	local func = assert(_writer[t],key)(msg)
	self[key] = func
	return func
end

setmetatable(encode_type_cache , {
	__index = function(self, key)
		local v = setmetatable({ _CType = key } , _encode_type_meta)
		self[key] = v
		return v
	end
})

function M.encode( message, t , func , ...)
	local encoder = c._wmessage_new(P, message)
	assert(encoder ,  message)
	encode_message(encoder, message, t)
	if func then
		local buffer, len = c._wmessage_buffer(encoder)
		local ret = func(buffer, len, ...)
		c._wmessage_delete(encoder)
		return ret
	else
		local s = c._wmessage_buffer_string(encoder)
		c._wmessage_delete(encoder)
		return s
	end
end

--------- unpack ----------

local _pattern_type = {
	[1] = {"%d","i"},
	[2] = {"%F","r"},
	[3] = {"%d","b"},
	[5] = {"%s","s"},
	[6] = {"%s","m"},
	[7] = {"%D","d"},
	[128+1] = {"%a","I"},
	[128+2] = {"%a","R"},
	[128+3] = {"%a","B"},
	[128+5] = {"%a","S"},
	[128+6] = {"%a","M"},
	[128+7] = {"%a","D"},
}

_pattern_type[4] = _pattern_type[1]
_pattern_type[8] = _pattern_type[1]
_pattern_type[9] = _pattern_type[5]
_pattern_type[10] = _pattern_type[7]
_pattern_type[11] = _pattern_type[7]
_pattern_type[128+4] = _pattern_type[128+1]
_pattern_type[128+8] = _pattern_type[128+1]
_pattern_type[128+9] = _pattern_type[128+5]
_pattern_type[128+10] = _pattern_type[128+7]
_pattern_type[128+11] = _pattern_type[128+7]


local function _pattern_create(pattern)
	local iter = string.gmatch(pattern,"[^ ]+")
	local message = iter()
	local cpat = {}
	local lua = {}
	for v in iter do
		local tidx = c._env_type(P, message, v)
		local t = _pattern_type[tidx]
		assert(t,tidx)
		tinsert(cpat,v .. " " .. t[1])
		tinsert(lua,t[2])
	end
	local cobj = c._pattern_new(P, message , "@" .. table.concat(cpat," "))
	if cobj == nil then
		return
	end
	c._add_pattern(GC, cobj)
	local pat = {
		CObj = cobj,
		format = table.concat(lua),
		size = 0
	}
	pat.size = c._pattern_size(pat.format)

	return pat
end

setmetatable(_pattern_cache, {
	__index = function(t, key)
		local v = _pattern_create(key)
		t[key] = v
		return v
	end
})

function M.unpack(pattern, buffer, length)
	local pat = _pattern_cache[pattern]
	return c._pattern_unpack(pat.CObj , pat.format, pat.size, buffer, length)
end

function M.pack(pattern, ...)
	local pat = _pattern_cache[pattern]
	return c._pattern_pack(pat.CObj, pat.format, pat.size , ...)
end

function M.check(typename , field)
	if field == nil then
		return c._env_type(P,typename)
	else
		return c._env_type(P,typename,field) ~=0
	end
end

--------------

local default_cache = {}

-- todo : clear default_cache, v._CObj

local function default_table(typename)
	local v = default_cache[typename]
	if v then
		return v
	end

	v = { __index = assert(decode_message(typename , "")) }

	default_cache[typename]  = v
	return v
end

local decode_message_mt = {}

local function decode_message_cb(typename, buffer)
	return setmetatable ( { typename, buffer } , decode_message_mt)
end

function M.decode(typename, buffer, length)
	local ret = {}
	local ok = c._decode(P, decode_message_cb , ret , typename, buffer, length)
	if ok then
		return setmetatable(ret , default_table(typename))
	else
		return false , c._last_error(P)
	end
end

local function expand(tbl)
	local typename = rawget(tbl , 1)
	local buffer = rawget(tbl , 2)
	tbl[1] , tbl[2] = nil , nil
	assert(c._decode(P, decode_message_cb , tbl , typename, buffer), typename)
	setmetatable(tbl , default_table(typename))
end

function decode_message_mt.__index(tbl, key)
	expand(tbl)
	return tbl[key]
end

function decode_message_mt.__pairs(tbl)
	expand(tbl)
	return pairs(tbl)
end

local function set_default(typename, tbl)
	for k,v in pairs(tbl) do
		if type(v) == "table" then
			local t, msg = c._env_type(P, typename, k)
			if t == 6 then
				set_default(msg, v)
			elseif t == 128+6 then
				for _,v in ipairs(v) do
					set_default(msg, v)
				end
			end
		end
	end
	return setmetatable(tbl , default_table(typename))
end

function M.register(buffer)
	c._env_register(P, buffer)
end

function M.register_file(filename)
	local f = assert(io.open(filename , "rb"))
	local buffer = f:read "*a"
	c._env_register(P, buffer)
	f:close()
end

function M.enum_id(enum_type, enum_name)
	return c._env_enum_id(P, enum_type, enum_name)
end

function M.extract(tbl)
    local typename = rawget(tbl , 1)
    local buffer = rawget(tbl , 2)
    if type(typename) == "string" and type(buffer) == "string" then
        if M.check(typename) then
            expand(tbl)
        end
    end

    for k, v in pairs(tbl) do
        if type(v) == "table" then
            M.extract(v)
        end
    end
end

M.default=set_default

function M.new(typename, tbl)
    local tbl = tbl or {}

	return setmetatable(tbl , default_table(typename))
end

function M.serializeToString(msg)
    return decode(msg._CType, msg)
end

return M




addressbook.proto
<span style="font-size:18px;">// See README.txt for information and build instructions.
syntax = "proto2";
package tutorial;

enum Cmd
{
    GAMECMD  = 1;
    SCENECMD = 2;
}

message Person {
  required string name = 1;
  required int32 id = 2;        // Unique ID number for this person.
  optional string email = 3;

  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  message PhoneNumber {
    required string number = 1;
    optional PhoneType type = 2 [default = WORK];
  }

  repeated PhoneNumber phone = 4;
  repeated int32 test = 5 [packed=true];
  optional uint32 score = 6;
  optional PhoneType tel = 7;
  repeated string params = 8;
  optional Cmd cmd1 = 9[default = GAMECMD];
  required Cmd cmd2 = 10[default = GAMECMD];
  optional bytes data = 11;

  extensions 100 to max; 
}

message Ext {
  extend Person {
    optional int32 test = 100;
  }
}

// Our address book file is just one of these.
message AddressBook {
  repeated Person person = 1;
}
</span>


main.cpp
#include <stdio.h>
#include "addressbook.pb.h"

extern "C"
{
  #include <lua.h>
  #include <lauxlib.h>
  #include <lualib.h>
}

int parseWithLuaPBC(lua_State* L, std::string& strMsg)
{
    lua_getglobal(L, "parseWithPBC");
    lua_pushstring(L, strMsg.c_str());
    lua_call(L, 1, 1);

    int ret = (int)lua_tointeger(L, -1);
    lua_pop(L, 1);

    return ret;
}

int add(lua_State* L)
{
    lua_getglobal(L, "add");
    lua_pushnumber(L, 1);
    lua_pushnumber(L, 1);
    lua_call(L, 2, 1);

    int ret = (int)lua_tointeger(L, -1);
    lua_pop(L, 1);

    printf("ret : %d\n", ret);

    return 0;
}

static int parseFromPBC(lua_State* L)
{
    const char* pmsg = luaL_checkstring(L, 1);
    std::string strMsg = pmsg; 

    tutorial::Person p;
    p.ParseFromString(strMsg);

    printf("%d\n", (int)p.id());
    printf("%s\n", p.name().c_str());
    printf("%d\n", (int)p.tel());

    printf("%d\n", (int)p.phone_size());

    for (int i = 0; i < (int)p.phone_size(); ++i)
    {
        const tutorial::Person_PhoneNumber& phone = p.phone(i);
        printf("number : %s\ttype : %d\n", phone.number().c_str(), (int)phone.type());
    }

    for (int i = 0; i < (int)p.params_size(); ++i)
    {
        const std::string& str = p.params(i);
        printf("param %s\n", str.c_str());
    }

    const std::string& strData = p.data();
    printf("data %s\n", strData.c_str());

    return 0;
}

int main( void )
{
    lua_State *L = luaL_newstate();
    luaL_openlibs( L );
    
    lua_register(L, "parseFromPBC", parseFromPBC);

    luaL_dofile(L, "test.lua");

    tutorial::Person p;
    p.set_name("chenjielin");
    p.set_id(101);
    p.set_email("chenjielin@xindong.com");

    std::string strMsg;
    p.SerializeToString(&strMsg);
    parseWithLuaPBC(L, strMsg);

    
    lua_close( L );
    return 0;
}

test.lua
local protobuf = require "protobuf"

addr = io.open("addressbook.pb","rb")
buffer = addr:read "*a"
addr:close()

protobuf.register(buffer)

t = protobuf.decode("google.protobuf.FileDescriptorSet", buffer)

proto = t.file[1]

person = {
	name = "Alice",
	id = 12345,
    phone = {
        { number = 17712345678, type = 1 },
        { number = 17712345678, type = 2 },
    },
    tel = 2,
    --[[
    params = {
        [1] = "chen",
        [2] = "jie",
        [3] = "lin"
    },
    --]]
    cmd2 = 1,
    data = "1010"
}

code = protobuf.encode("tutorial.Person", person)

parseFromPBC(code)

decode = protobuf.decode("tutorial.Person" , code)

--[[
for k,v in pairs(decode) do
    print(k,v)
    if type(v) == "table" then
        for ck, cv in pairs(v) do
            print("", ck, cv)
        end
    end
end
--]]

print("cmd1", decode.cmd1)
print("data", decode.data)

print("params len", #decode.params)

if getmetatable(decode) then
    local mt = getmetatable(decode)
    for k,v in pairs(mt) do
        print(k,v)
        if type(v) == "table" then
            for ck,cv in pairs(v) do
                print("", ck,cv)
            end
        end
    end
end

--print(decode.name)
--print(decode.id)


print("###################")

local msg = protobuf.new("tutorial.Person")

print(msg._CType)
print(msg.params)
print(msg.phone)
print(msg.cmd1)
print(msg.cmd2)

for k,v in pairs(msg) do
    print(k,v)
end

function parseWithPBC(data)
    print("---------")
    local msg = protobuf.decode("tutorial.Person", data)
    if msg then
        print(msg.cmd1)
        print(msg.name)
        print(msg.email)
    end

    return 1
end


Makefile
TARGET=test
TARGET:main.o addressbook.pb.o
	g++ -I/usr/local/include/ -L/usr/local/lib/ -lm -DLUA_USE_READLINE main.o addressbook.pb.o -o $(TARGET) -g -Wl,-E -ldl -llua -lprotobuf -Wl,-Bstatic -Wl,-Bdynamic -lpthread
main.o:main.cpp
addressbook.pb.o:addressbook.pb.cc
clean:
	rm -rf $(TARGET)
	rm -rf *.o
clear:
	rm -rf core*
	rm -rf *.pb*
	

生成pb脚本
proto.sh
#!/bin/bash

protoc -o addressbook.pb addressbook.proto
protoc --cpp_out=./ addressbook.proto



5运行效果






windows环境下编译使用PBC库 PBC :Pairing-Based Cryptography 由于最近需要在windows+vs2008环境下使用PBC静态库,上网查找发现编译PBC库的资料并不多,为方便今后查阅,做总结如下: PBC库是基于linux环境下编写的,但自0.5.10版本开始,便可以在windows环境下编译。 1、要编译PBC库,首先必须安装MinGW和Msys两个软件(可直接从网上下载,与一般安装软件无 阅读详情

相关推荐

基于身份的加密(IBE)——使用PBC库实现 Identity Based Encryption(IBE) - Pairings Based Crypto (PBC) library

基于身份的加密(IBE)——使用PBC库实现 Identity Based Encryption(IBE) - Pairings Based Crypto (PBC) library

rock4you 7841

lua 调用c模块

c函数声明要符合类型:typedef int (*lua_CFunction) (lua_State *L); 1.在c代码运行环境下执行lua代码。#include <stdio.h> #include <string.h> #include <lua.h> #include <lauxlib.h> #include <lualib.h>static int cadd(lua_State* L)

renyican的博客 481

PLL锁相环基础知识(一)

本文介绍了锁相环(PLL)的核心组件及其工作原理,重点阐述了压控振荡器(VCO)的结构与调谐机制。VCO作为PLL的关键部分,通过变容二极管实现频率调谐,但易受温度、电压等因素影响稳定性。文章详细讲解了VCO的谐振电路原理、硅基集成方案,以及通过分频器和调制器实现的频率控制技术。特别分析了整数型和分数型N分频器的差异,指出高阶德尔塔-西格玛调制器可有效降低分数杂散。文章还探讨了预分频器的应用及其对频率分辨率的影响,揭示了PLL通过反馈环路实现频率锁定的基本原理。

weixin_49761275的博客 3047

C 编写lua模块(1)

问题: 今天在看云风的Proto Buffers in Lua时,有个疑问: 在看protobuf.lua文件时,看到开头有local c = require "protobuf.c" 这一行,去文件目录下搜索了一下protobuf.c,但是根本就没有这个文件,我就感觉不是很明白,但是有一个pbc-lua.c文件,这两个之间有什么关系? 解决: 网上google一番,找到几篇挺好的

思考的智慧,知识源于思考 3580

Codex 命令行高效操作指南

本文详细介绍了Codex命令行工具的高效使用方法,包括安装配置、核心参数解析和实战技巧。通过`codex complete`、`codex explain`等指令,开发者可以快速生成代码、调试错误和重构项目,显著提升开发效率。特别推荐使用`--temperature`和`--max-tokens`参数优化生成结果。

weixin_29201313的博客 537

告别手册!S32K3XX的eMIOS实战:从GPT定时到PWM输出,一个通道搞定电机控制

本文深入探讨了NXP S32K3XX系列MCU的eMIOS模块在电机控制中的高效应用。通过单通道实现PWM生成、输入捕获和定时中断三大功能,展示了如何简化BLDC电机控制硬件设计。文章结合RTD库与寄存器级编程,提供动态模式切换和性能优化方案,显著降低CPU负载。

weixin_42522374的博客 150

[寒江孤叶丶的Cocos2d-x之旅_35]在Cocos2d-Lua中使用ProtoBuf (Xcode配置方法)

数据传输格式有很多种最常见XML和Json,这两种格式生成速度非常快,但是解析的效率却很低。尤其在数据量非常大的情况下,会卡住好半天。并且这种格式的传输也会使得传输所耗费流量变大。解析效率最高,传输消耗流量最小的数据格式自然是Buffer。很多公司都封装过自己的Buffer流传输的模块。 Google公司将他们封装的Buffer流模块给贡献了出来!也就是我这里所提到的Protobuf。

寒江孤叶丶的游戏生涯 3337

abaqus2matlab的安装与使用:如何用matlab提取abaqus的odb结果

官网abaqus2matlab官网地址matlab社区地址matlab社区地址在这里可以看到.m文件的源码论文:Abaqus2Matlab: A suitable tool for finite element post-processingabaqus2matlab可以处理.inp、.fil、.odb三种类型的文件。.inp文件:处理功能就在于只是单纯的输出inp文件,由于我自己写了自己的函数,不需要用到这个功能。

qianxin1234的博客 2025

Require模块入门二

Require模块入门二 1.工程结构 -Webapp --Js   ----lib   ----require.js   ----requirepart(app)   ----one.js   ----reqmain.js(app.js) --reqtest(app.html)       2.代码分析 2.1.reqtest.html  html>     he

yhm_js的专栏 350

开坑!双向逆变电源实操系列--第一节PFC

文章摘要 本文介绍了PFC(功率因数校正)的基本概念及其重要性。PFC电路通过储能和功率因数校正两大功能,解决交流电小电压大电流的问题,并减少无功电流损耗。文章对比分析了无源PFC(电感串联式、填谷式、LC谐振式)和有源PFC(升压型、交错并联、图腾柱式)的拓扑结构及适用场景。针对2400W双相逆变电源设计,作者选择图腾柱PFC拓扑,详细阐述了设计思路,包括电气参数计算、性能指标设定、技术重点及风险预判。文章还提供了主电路参数定制计算方法,如BOOST电感值的推导过程,为电源工程师提供实用参考。

lyzh971103的博客 2569

华为OD新系统机试真题 - 配置操作失败数量统计

华为OD机试新系统 4月8号【配置操作失败数量统计】,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。华为OD机试真题【配置操作失败数量统计】。

qq_45776114的博客 1178

使用 pbc

使用pbc 标签: linuxluaC++pbc 2016-08-08 16:56 1486人阅读 评论(0) 收藏 举报  分类: lua linux(1)  C++(1)  版权声明:本文为博主原创文章,未经博主允许不得转载。 目录(?)[+] 1环境 Linux CentOS 7 lua 5.3

boshuzhang的专栏 2216

Python数据可视化 Pyecharts 制作 Map 地图

大家好,我是Mr数据杨。想象一下,作为一名军师,如诸葛亮或郭嘉,'Map’就如同那战争的沙盘,兵马行动的轨迹,都需要准确的地图作为基础。‘基本设置’,就如同摆设这张战争沙盘,规定棋子的起始位置。‘数据配置选项’和’地图数据项’,就好比是军师们手中的情报,了解各路诸侯的兵力、粮草、地形等重要信息,以便于他们更好地布局。‘Demo’则代表着练兵之地,军师们可以在此基于已有数据,试验各种战术。

Mr数据杨 4万+

xlua使用pbc

之前学了xlua整合proto-gen-lua,由于proto-gen-lua使用的lua5.1,相对于现在的5.3来说改动较大。 有兴趣的可以参考下:https://gitee.com/U3DDevelopment/xlua-framework 今天讲述一下xlua整合pbc的过程: 1.首先是xlua整合pbc编译xlua.dll pbc的下载地址:https://github.com...

gqj108的博客 2573

如何通过 GitHub Actions 使用 SSH 自动化部署到阿里云 ECS 实例

通过 GitHub Actions 和 SSH 自动化部署,可以显著提高你的开发效率和部署的可靠性。本文介绍了如何生成 SSH 密钥、将公钥添加到阿里云 ECS 实例、将私钥添加到 GitHub Secrets,以及编写 GitHub Actions 工作流来实现自动化部署。希望这篇文章对你有所帮助!

吃面不喝汤的博客 1514

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

PBC密码学库使用指南

PBC(Pairing-based cryptography)库是一个免费的C库(根据GNU Lesser General Public许可证发布),它建立在GMP库的基础上,执行基于配对的加密系统的数学运算 安装教程 该安装教程当前仅适用Linux平台的用户,具体可参考官方文档 下载 首先,在官网下载安装包,可以看到有多个不同的包,这里下载pbc-0.5.14.tar.gz,这是因为安装环境是在Linux平台(如有必要,本文档后续会更新在Windows平台的安装教程) 编译和安装库 对于大多数库,解压缩

Drawlonely的博客 1万+

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

lua pbc 使用

lua pbc 先要将proto文件编译成.pb文件,然后再动态绑定实现lua protobuffer,这就需要了解云风做的pbc的项目,地址为:https://github.com/cloudwu/pbc/blob/master/binding/lua/README.md 在github上下载pbc,https://github.com/cloudwu/pbc 具体的方式是,下载pbc的项目;在...

linxinfa的专栏 2979

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

PBC下载、安装及基本使用

PBC下载、安装及基本使用 下载 安装 在下PBC之前需要GMP库 在官网找到相应的包进行安装 我采用源码安装,将下载的pbc-0.5.14.tar.gz解压,并进入解压后的目录 # 对即将安装的软件进行配置,检查当前的环境是否满足要安装软件的依赖关系,根据提示先将依赖包安装好 ./configure # 对源码进行编译 make # 将编译好的程序安装到相应目录,默认的目录...

hhh_2333 4110

【密码学库使用】PBC-for-Go

最近做实验需要用到密码学库PBC(Pairing-Based Cryptography),pbc 包提供了构建基于配对的密码系统的结构。它是围绕 Ben Lynn 编写的基于配对的密码学(PBC)库的封装(且实验使用Go编写,因此介绍一下pbc的go环境安装。强烈推荐使用Linux环境,题主Windows和Mac都曾安装过,但只有Linux可以做到无痛安装。

qq_46063517的博客 4133

PBC密码库安装及使用教程

PBC库主要用来实现双线性映射密码学运算,本文主要介绍了C++ PBC库的安装、使用流程,并基于PBC实现LSSS算法。

tutu_hu的博客 4710

在golang中使用PBC密码库

1. 安装系统     使用Ubuntu或Mint操作系统        (1) GIT 和Go安装     安装git    sudo apt-get install git     安装golang      从https://www.golangtc.com/download 下载go      sudo tar -zxf go1.9.linux-amd64.tar.gz 

lhwhit的专栏 4028

Windows下使用MinGW编译生成的PBC库

1.  使用环境: Windows 7 Ultimate64bit,Visual Studio 2010,pbc-0.5.12。 2.  使用说明: 本文使用的PBC库是网络上使用minGW编译好的libpbc.a及相关链接库文件。 3.  使用步骤: 1.    建立VS2010 C++项目工程,将“所需源文件”文件夹中的include文件、libpbc.a、libgcc.a、libg

Trust Bo 4394

pbc 的使用

這兩天在準備lua開發的基本組件。 其中一個重要的部份就是lau要能讀寫字符串數據,即序列化的數據。這樣才能和其他服務做通用處理。 現在通用的序列協議莫過於google的protobuf了。 上網找了一圈,發現lua的protobuf 解析文件都是第三方。有兩種是拿python開發的,問題也還不少。 國內有牛人雲風開發的一個pbc的版本。個人做了基本嘗試,發現python版本的問題多多。2

ShiningStarPxx的专栏 3023

pbc的使用(Windows)

最近在使用tolua# & LuaFramework框架做项目集成中用到了pbc 发现pbc的使用的文档不是太多,此处写一下个人的使用的总结,后面不断的完善 首先贴几个讲解pbc使用的博客: 1.http://blog.csdn.net/houjia159/article/details/45197955 2.http://blog.csdn.net/yeungxuguang/articl

涂鸦之笔,不登大雅之堂。 3501

Windows下使用VS2017调用PBC

**Windows下使用VS2017调用PBC** 小白一枚,摸索了一天终于弄清楚了如何用vs2017来调用pbc!希望能够帮助大家节约安装pbc库的时间!这里大家不需要下载pbc库,下面给出的文件中的include已经包含了gmp.h等头文件。 需要下载的文件:链接:https://pan.baidu.com/...

daiyugege的博客 3043

PBC 开源项目使用教程

PBC 项目的目录结构如下: ``` pbc/ ├── benchmark/ ├── binding/ ├── compat/ ├── doc/ ├── example/ ├── lua/ ├── Makefile ├── README.md ├── src/ └── test/ ``` - **benchmark/**: 包含性能测试相关的文件。 - **binding/**: 包含与其他语

gitblog_00730的博客 622
上一篇: c++使用luabind示例
cjl1201
博客等级 码龄14年 2粉丝 6原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值